2

I am following the Authorization Code Flow (3-legged OAuth) documentation and I am now at step 3 where I need to use the authorization code in order to recieve an access token from LinkedIn. In the project I am using node.js, typescript and the node-fetch library. The following function creates a body with content type x-www--form-urlencoded since this is content type which LinkedIn require.

async function GetAccessToken(data: any) {

    let body: string | Array<string> = new Array<string>();
    for (let property in data) {
        let encodedKey = encodeURIComponent(property);
        let encodedValue = encodeURIComponent(data[property]);
        body.push(encodedKey + "=" + encodedValue);
    }
    body = body.join("&");

    const response = await fetch("https://www.linkedin.com/oauth/v2/accessToken", {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
        body: body
    }).then((res: any) => {
        console.log("Result", res);
    });
    return response;
}

I do not recieve any errors and the response status is 200 but the response values I recieve are:

size: 0,
timeout: 0,

and what LinkedIn promise is:

access_token
expires_in

When I post the url with my parameters using postman the request goes through and I recieve the correct data which indicates the problem lies within my request function and not my values.

Any help is appreciated!

Shrimpis
  • 123
  • 2
  • 8

1 Answers1

0

You need add all headers from postman

const urlencoded = new URLSearchParams();
urlencoded.append("client_id", env.LINKEDIN_CLIENT_ID);
urlencoded.append("client_secret",env.LINKEDIN_CLIENT_SECRET);
urlencoded.append("grant_type", "authorization_code");
urlencoded.append("code", code);
urlencoded.append(
  "redirect_uri",
  "http://localhost:3000/api/auth/linkedin-custom"
);

const accessTokenPromise = await fetch(
  "https://www.linkedin.com/oauth/v2/accessToken",
  {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: urlencoded,
  }
);
Tyler2P
  • 2,324
  • 26
  • 22
  • 31