Issue with Decoding Access Token when passing from NextJS to Flask

Tokens issued by login/logout system on NextJS application are not being decoded correctly by my Python API.

I am using the basic NextJS auth concept here. I have created an application called “Test” using the Client ID and Client Secret from the Test Application. Login/logout works perfectly! Client credentials flow is not enabled on this application.

I then create an Auth0 API called Trial (this creates a new application Trial (Test Application)) and then configure my Flask application based on this tutorial here. If I use the sample bearer token in the Trial API Auth0 dashboard under the “Test” tab, the authentication works as described.

The issue is from the exchange below. The token passed from NextJS to my Flask app is not decoded correctly. Any ideas here?

// pages/api/products.js
import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0';

export default withApiAuthRequired(async function products(req, res) {
  // If your Access Token is expired and you have a Refresh Token
  // `getAccessToken` will fetch you a new one using the `refresh_token` grant
  const { accessToken } = await getAccessToken(req, res, {
  });
  const response = await fetch('https://api.example.com/products', {
    headers: {
      Authorization: `Bearer ${accessToken}`
    }
  });
  const products = await response.json();
  res.status(200).json(products);
});

Think I figured it out from their examples here

Authorization params needs to include the audience.

// pages/api/auth/[...auth0].js
import { handleAuth, handleLogin } from "@auth0/nextjs-auth0";

export default handleAuth({
  async login(req, res) {
    try {
      await handleLogin(req, res, {
        authorizationParams: {
          audience: <AUDIENDCE URL>, 
          // Add the `offline_access` scope to also get a Refresh Token
          scope: "openid profile email", // or AUTH0_SCOPE
        },
      });
    } catch (error) {
      res.status(error.status || 400).end(error.message);
    }
  },
});

If this doesn’t work, go to the APIs section in the Trial (Test Application) application folder on the Auth0 dashboard and click APIs and enable the Auth0 management API

1 Like

Hey @dylan6 thanks for following up with the solution :white_check_mark:

That’s correct though, unless the access token contains a valid audience value it will be an opaque token and therefore not able to be decoded. Some helpful resources for future reference:

Cheers!