@auth0/nextjs-auth0 tokens and external api help

Welcome to the Auth0 Community @jseneris!

First of all, if you want to protect an external/custom API with Auth0, you need to register your API in your Auth0 tenant as described here: Register APIs

After you’ve done the above, you will be ready to request Access Tokens with the audience of that custom API. You have relevant documentation here: Get Access Tokens

Now, you need to set the audience of your custom API when you make the /authorize call to authorize the user. For example, if you are using an Authorization Code Flow, you will need to make a call like this:

https://YOUR_DOMAIN/authorize?
    response_type=code&
    client_id=YOUR_CLIENT_ID&
    redirect_uri=https://YOUR_APP/callback&
    scope=SCOPE&
    audience=API_AUDIENCE&
    state=STATE

The audience parameter is the one you need to set to your custom API.

I highly suggest you read Call Your API Using the Authorization Code Flow if that’s the flow you are going to implement.

Regarding Next.js Auth0 SDK specifics, I admit I am not experienced with this very SDK, but after some googling, I think I’ve found what you need. You would need to pass the audience directly to the handlelogin method, or use environment variables instead as documented in our GitHub repository: nextjs-auth0/EXAMPLES.md at main · auth0/nextjs-auth0 · GitHub :

// 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: 'https://api.example.com/products', // or AUTH0_AUDIENCE
          // Add the `offline_access` scope to also get a Refresh Token
          scope: 'openid profile email read:products' // or AUTH0_SCOPE
        }
      });
    } catch (error) {
      res.status(error.status || 400).end(error.message);
    }
  }
});

3 Likes