Retrieve LinkedIn access token
Asked Answered
T

2

8

I'm trying to get linkedIn oauth2 access token but I stuck on making last request to https://www.linkedin.com/oauth/v2/accessToken

const body = new URLSearchParams([
  ['grant_type', 'authorization_code'],
  ['code', code],
  ['redirect_uri', 'http://localhost:3000/'],
  ['client_id', CLIENT_ID],
  ['client_secret', CLIENT_SECRET]
]);
const headers = new Headers({'Content-Type': 'x-www-form-urlencoded'}); 

window.fetch('https://www.linkedin.com/oauth/v2/accessToken', method: 'POST',body, headers)
.then(response => response.json())
.then(data => {
// rest of code
})

LinkedIn returns

Fetch API cannot load https: //www.linkedin.com/oauth/v2/accessToken. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: //localhost:3000' is therefore not allowed access. The response had HTTP status code 404. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

so I tried to make request in 'no-cors' mode. I've got 200 but I can't get body of response,status is 0, body is null and response.json() throws SyntaxError: Unexpected end of input.

Tropic answered 20/9, 2017 at 8:38 Comment(2)
I have the same problem.Incorrigible
i have the same problemMelodramatize
T
2

For anyone who came across this problem. We solved it by passing data from LinkedIn (code) to our backend. Backend have no need to send any preflight OPTIONS requests and can get access token without problem.

Tropic answered 24/5, 2018 at 8:47 Comment(0)
M
0

I found out your issue, The Content-Type header value is not correct.

It's meant to be

const headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});

NOT

const headers = new Headers({'Content-Type': 'x-www-form-urlencoded'});

DOCS: https://developer.linkedin.com/docs/oauth2 (Step 3)

Melodramatize answered 19/5, 2018 at 12:26 Comment(1)
It still doesn't work. Failed to load linkedin.com/oauth/v2/accessToken: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. And if I add header {'Access-Control-Allow-Origin': '*'} it fails on preflight...Tropic

© 2022 - 2024 — McMap. All rights reserved.