2

I am trying to hit a Linkedin accessToken API but always facing CORS error in react js (frontend). Samething works while direct hit in URL bar or through postman. This is the error I am getting:

Access to fetch at 'https://www.linkedin.com/oauth/v2/accessToken' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

My Code is:

const queryParams = querystring.stringify({
  redirect_uri: process.env.REACT_APP_LINKEDIN_REDIRECT_URI,
  client_id: process.env.REACT_APP_LINKEDIN_CLIENT_ID,
  client_secret: process.env.REACT_APP_LINKEDIN_CLIENT_SECRET,
  grant_type: 'authorization_code',
  code: code,
});
const headers = {
  'Content-Type': 'application/x-www-form-urlencoded',
};


const response = await fetch(`https://www.linkedin.com/oauth/v2/accessToken`, {
  method: 'POST',
  headers: headers,
  body: queryParams,
});

`

Ankit Shah
  • 862
  • 1
  • 7
  • 22
  • Have you tried to add `mode: 'no-cors'` to the options in `fetch`? (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch ) – Me.Name Sep 20 '21 at 12:31
  • @Me.Name Yes I did, still same – Ankit Shah Sep 20 '21 at 12:33
  • @Me.Name Yes I did, It won't show cors error but also at the same time, it does not show anything in response. i.e. there is no response – Ankit Shah Sep 20 '21 at 12:41
  • Does this answer your question? [How does Access-Control-Allow-Origin header work?](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work) – zero298 Sep 20 '21 at 13:54

2 Answers2

2

The API responses do not include Access-Control-Allow-Origin header so your browser is prohibiting requests to those APIs.

You have 2 choices here:

  1. obtain the access token on the backend using a 2-legged OAuth flow
  2. or use a 3-legged OAuth flow which requires you to redirect the user's browser to Linkedin's site

From a security perspective, you should not distribute the client secret in HTML/JS files.

adambene
  • 1,065
  • 9
  • 14
1

The Linkedin API doesn't allow requests from locations such as localhost using the CORS header 'Access-Control-Allow-Origin'. https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

If you really need it, you could always have your proxy server or use something like https://cors-anywhere.herokuapp.com/.

edarv
  • 336
  • 5