Getting unauthorized/access_denied on getting token using refresh token

This is a code snippet on my Nextjs project using nextauth to get new tokens followed this thread

async function refreshAccessToken(token: any) {
  try {
    const url =
      `${process.env.AUTH0_ISSUER}/oauth/token?` +
      new URLSearchParams({
        client_id: process.env.AUTH0_CLIENT_ID || '',
        client_secret: process.env.AUTH0_CLIENT_SECRET || '',
        grant_type: 'refresh_token',
        refresh_token: token.refreshToken,
        scope: 'offline_access',
      });
    const response = await fetch(url, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
    });

    const refreshedTokens = await response.json();

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

    return {
      ...token,
      accessToken: refreshedTokens.access_token,
      accessTokenExpires: Date.now() + refreshedTokens.expires_in * 1000,
      refreshToken: refreshedTokens.refresh_token ?? token.refreshToken, // Fall back to old refresh token
    };
  } catch (error) {
    return {
      ...token,
      error: 'RefreshAccessTokenError',
    };
  }
}

I kept getting { error: 'access_denied', error_description: 'Unauthorized' } no matter how I changed Application Type, Token Endpoint Authentication Method or other settings.

Hi @wkjljadlskfjklasjflw ,

Welcome to the Auth0 Community!

I understand that you have encountered the 401 Unauthorized error when trying to get a new access token using a refresh token.

After testing this myself, I could successfully get a new access token using a refresh token. The only way I could reproduce the 401 Unauthorized error is when I used an incorrect client_id and/or client_secret in my request.

Given that, could you please double-check that your client_id and client_secret values are correct?

Please let me know your findings.

Thank you.

Hi @rueben.tiow ,

Thanks for the response. Turns out that I have to put all params to request body instead of URLParams, also need to change Content-Type to application/json and it works.

1 Like

Hi @wkjljadlskfjklasjflw,

Thank you for your response, and I’m glad you managed to get the request working!

Please reach out if you have any additional questions.

Thank you.