Unable to get access Token linkedin Oauth
Asked Answered
V

1

8

I know some will put comment like this post is duplicate of so many questions, but I've tried many ways to achieve Access Token in linkedin Oauth. Explaining what i tried.

1) I'm following it's official doc's Linkedin Oauth2

2) I'm successfully getting Authorization code from step 2 and passing that code to step 3 for exchanging Auth code for getting Access Token. But i'm getting following error {"error_description":"missing required parameters, includes an invalid parameter value, parameter more than once. : Unable to retrieve access token : appId or redirect uri does not match authorization code or authorization code expired","error":"invalid_request"}

3) According to some links i need to set content-type in the header.Link which tells to set content-type is missing

4)Then i tried calling https://www.linkedin.com/uas/oauth2/accessToken this service instead of POSt to GET. And passing data as queryParams.

5) Some link says oauth code expires in 20 sec, So i've checked, i'm making call for access token in less that 1 sec.

6) And if i pass data in Body params like as below and used url as https://www.linkedin.com/uas/oauth2/accessToken

var postData = {
                grant_type: "authorization_code",
                code: authCode,
                redirect_uri: 'https%3A%2F%2Foauthtest-mydeployed-app-url',
                client_id: 'my_client_id',
                client_secret: 'secret_key'
            };

7) With Get call my url i tried https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code='+authCode+'&redirect_uri=https%3A%2F%2Foauthtest-mydeployed-app-url&client_id=my_client_id&client_secret=secret_key

Still i'm getting Error even though status code is 200, i'm getting that error(with GET api) and If POSt by passing postData in body i'm getting bad request 400 status code

Not understanding why m I not getting access code. I've read many solutions. Sharing code as requested.

sap.ui.define([
	"sap/ui/core/mvc/Controller",
	"sap/m/MessageToast"
], function (Controller, MessageToast) {
	"use strict";

	return Controller.extend("OauthTest.OauthTest.controller.View1", {
		onPress: function (evt) {
			var sPath =
				'https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=my_client_id&redirect_uri=https%3A%2F%2Foauthtest-mydeployed-app-url&state=DCEeFWf45A53sdfKef424&scope=r_basicprofile';
			window.location.href = sPath;
            var oRouter = new sap.ui.core.UIComponent.getRouterFor(this);
			oRouter.navTo("View2", {
				"username": "Test"
			});
			MessageToast.show(evt.getSource().getId() + " Pressed");
		},
		
		//after user allows access, user will be redirected to this app with code and state in URL
		//i'm fetching code from URL in below method(call is happening in max.569ms)
		
		onAfterRendering: function () {
			var currentUrl = window.location.href;
			var url = new URL(currentUrl);
			var authCode = url.searchParams.get("code");
			if (authCode !== undefined && authCode !== null) {
				var postData = {
					grant_type: "authorization_code",
					code: authCode,
					redirect_uri: 'https%3A%2F%2Foauthtest-mydeployed-app-url',
					client_id: 'my_client_id',
					client_secret: 'secret_key'
				};
				
			/*	var accessTokenUrl = 'https://www.linkedin.com/uas/oauth2/accessToken?grant_type=authorization_code&code=' + authCode +'&redirect_uri=https%3A%2F%2Foauthtest-mydeployed-app-url&client_id=my_client_id&client_secret=secret_key';*/

				var accessTokenUrl = 'https://www.linkedin.com/uas/oauth2/accessToken';

				$.ajax({
					url: accessTokenUrl,
					type: "POST",
					beforeSend: function (xhr) {
						xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
					},
					data: postData,
					success: function (data, textStatus, jqXHR) {
						console.log(data);
						alert('success');
					},
					error: function (jqXHR, textStatus, errorThrown) {
						console.log(errorThrown);
						alert('error');
					}
				});
			}
		}

	});
});

Help will be appriciated..!!!

Veasey answered 25/9, 2018 at 14:54 Comment(5)
as mention in error, you have to check below things 1) Make sure access code is not expired. 2) URL for generate access token will be: linkedin.com/oauth/v2/accessToken 3) Method: POST 4) POSTFIELDS are as below i) grant_type='authorization_code' ii) code="<ur access code>" iii) redirect_uri=<exacttly same URL were access code is generated> iv) client_id=<LINKEDIN_CLIENT_ID> v) client_secret=<LINKEDIN_CLIENT_SECRET>Hirsh
Below is sample code (in PHP) for your reference. $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,"linkedin.com/oauth/v2/accessToken"); curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch, CURLOPT_POSTFIELDS,"grant_type=authorization_code&code=".$code."&redirect_uri=".env('LINKEDIN_REDIRECT_URL')."&client_id=".env('LINKEDIN_CLIENT_ID')."&client_secret=".env('LINKEDIN_CLIENT_SECRET')); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec ($ch); curl_close ($ch);Hirsh
@KetavChotaliya, i tried with post according to your 1st comment, in that case i'm getting bad request and status code as 400. and we need to pass content-type in the header too. and i checked my access code is not getting expired thoughVeasey
Need to debug carefully...flow is same as I mentioned above. If possible share your code.Hirsh
@KetavChotaliya added code for more clarityVeasey
V
4

Finally I am happy to post my answer after so much search. Every step I did is correct only, but one thing I was missing here like, Linkedin API doesn't supports CORS.

I tried implementing Javascript SDK, that works like charm. But API wasn't. Then I found very helpful Link which says I need to implement Rest API from backend by allowing CORS, not from front end.

Make sure to follow all the points which I mentioned above in my post. And for Allow CORS follow this link. You will get data but only basic profile of user according to LinkedIn Terms data can be accessible

Hope this post may help someones time to search more

Veasey answered 26/9, 2018 at 17:21 Comment(1)
first thing I was going to say was that javascript call to the api would probably fail due to browser protections on CORS yap. anyway, my issue on my side was just a time problem. #28095426Twinned

© 2022 - 2024 — McMap. All rights reserved.