Enabling app login to pass authorization code/user roles to API

I set up both a sample app and API in Auth0 (app-a and api-1). I’m running two node js servers locally, one for the app and one for the api. I can get a authorization token just fine. I was able to add this rule to login flow in Actions:

exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://api_1';
  if (event.authorization) {
    api.idToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
    api.accessToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
  }
}

That adds roles successfully to the idToken. However, I am struggling to find a way to pass those roles along when requesting an access token, which I am doing internally inside the app’s nodejs server file:

async function fetchAccessToken() {
    try {
        const response = await axios.post(`${process.env.AUTH_ISSUER_BASE_URL}/oauth/token`, {
            "client_id": process.env.AUTH_CLIENT_ID,
            "client_secret": process.env.AUTH_SECRET,
            "audience": "https://api_1",
            "grant_type": "client_credentials"
        }, {
            headers: {'Content-Type': 'application/json'}
        });
        return response.data;
    } catch (error) {
        console.error("Error fetching API access token:", error);
        return null;
    }
}

I get an access token but it doesn’t include the roles. I believe I need to supply an authorization code in the request. But I have not been able to succeed at doing that when creating another function using authorization_code as the grant type. (FYI, the client_id and client_secret are from app-1).

I have RBAC enabled for the API.

Hey @jon.nehring welcome to the community!

The action code you shared is only going to run when users log in - The fetchAccessToken function is getting an access token using the client credentials grant and is there for machine to machine.

For Node, you’ll want to look into using a library like express-openid-connect which does support a user login using the authorization code flow. You can find a quickstart here that goes over the general implementation. In particular, you will want to take a look at this example which show’s passing an audience param which is required in order to get an access token that can be used against your API.