401 unauthorized error throws when accessing oauth/token api from Nextjs App

Hi Team,

I am using free account of Auth0 to build Sitecore JSS client side application using NextJS and integrate SSO with Auth0 identity provider.
I am able to call the /authorize api and get the code for my app. And when I am trying get the access token from the code using api oauth/token, I am getting 401 unauthorized issue in my network tab in developer tools.

I tried all the solutions available in the community, but no use.

The below code is the sample code I had written to fetch token.

async function getAccessToken(code: any) {

try{

  const token_url = config.baseurl + "/oauth/token?" + 
          new URLSearchParams({
            client_id: config.client_id,
            client_secret: config.client_secret,
            grant_type: 'implicit',
            code: code
          });

  const response = await fetch(token_url, {
    headers: {
      'Content-Type' : 'application/json',
    },
    method: 'POST'
  });

  const token = await response.json();
  console.log(token.access_token);

  if(!response.ok){
    throw token;
  }

  return {
    accessToken : token.access_token
  };
}
catch(error){
  return {
    error: 'RefreshAccessTokenError',
  };
}

};

The below is the error message.

Please help me to resolve this issue.

Hi @glprasannakumar,

Welcome to the Auth0 Community!

I have reviewed your code snippet and noticed that you’re calling the /oauth/token endpoint with grant_type: 'implicit'. This is inconsistent with your login flow since you called the /authorize endpoint, which returned a code. If that happens, you performed the authorization code flow, which takes the grant_type: 'authorization_code'.

With that said, I recommend referring to the documentation below on getting an access token using the authorization code flow:

Lastly, if you haven’t already checked out our Auth0 Quickstarts, we have a list of SDKs that we support, including Next.js, which you refer to for an example or download the quickstart for a working sample.

Cheers,
Rueben

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.