Search code examples
javascriptreactjscorsfrontendlinkedin-api

CORS error on Linkedin oauth/v2/accessToken API from frontend


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,
});

`


Solution

  • 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.