Hi again @elian, and thank you for your patience!
For your first question, yes, it’s absolutely possible to include extra claims in the Access Token. The recommended way to do that is through actions.
A critical security practice here is to use a namespaced claim. Any custom claims you add should be prefixed with a unique URI to prevent them from colliding with standard OIDC claims. For example, use https://myapp.example.com/roles
instead of just roles
. Here is a link to our docs that explains the guidelines for namespaces.
Here’s how to create an Action to add a user’s roles to an access token.
- Navigate to the Actions Library:
- Go to your Auth0 Dashboard.
- On the left menu, go to Actions > Library.
- Create a New Action:
- Click Build Custom.
- Give it a name, like “Add Roles to Access Token”.
- Select the “Login / Post Login” trigger.
- Choose the Node.js version you prefer.
- Click Create.
- Add the Action Code
Here is an example of an action that adds a custom roles claim:
exports.onExecutePostLogin = async (event, api) => {
const namespace = 'https://my-app.example.com';
if (event.authorization) {
api.accessToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
}
}
I will also link you the docs for adding custom claims, in case you still need more help.
As for your 2nd question, the recommended pattern is to keep access tokens on the server and use Next.js API routes as a proxy between your frontend and your external resource API.
So you will retrieve the Access Token on the server with the getAccessToken method of the nextjs-auth0 SDK:
import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0';
export const GET = withApiAuthRequired(async function products(req) {
try {
// 1. Get the Access Token from the user's session.
const { accessToken } = await getAccessToken();
// 2. Use the token to call your external API.
const response = await fetch('https://my-external-api.com/products', {
headers: {
Authorization: `Bearer ${accessToken}`
}
});
if (!response.ok) {
return new Response('Failed to fetch from external API', { status: response.status });
}
const data = await response.json();
return Response.json(data);
} catch (error) {
return new Response(error.message, { status: 500 });
}
});
I hope this clarifies your questions!
Teodor.