Auth0 Action add user role to token

[Sample Use Cases: Actions with Authorization]

I am using nextjs with next-auth, and followed this guide above to add user role to token. Also assigned my account to an admin role under User Management/Roles on the auth0 dashboard

import useAuth from "../context/useAuth";

export default function Profile() {
  const { session, status, update } = useAuth();

  const role = !session?.user["https://<website>/roles"];

  if (session) {
    return (
      <>
        <div>Hello {session.user.name}</div>
        <div>Role: {role}</div>
      </>
    );
  }
}

useAuth.js

import { useSession, signIn, signOut } from "next-auth/react";

const useAuth = () => {
  const { data: session, status, update } = useSession();

  return { session, status, update, signIn, signOut };
};

export default useAuth;

I’m able to get the name from session.user.name, but can’t seem to retrieve the role as https:///roles returns an error and the page can’t even load. Is this the correct way to retrieve roles?

Running the test in auth0 actions with a random user returns this which seems to be working

[
  {
    "name": "https://<website>/roles",
    "target": "idToken",
    "type": "SetCustomClaim",
    "value": []
  },
  {
    "name": "https://<website>/roles",
    "target": "accessToken",
    "type": "SetCustomClaim",
    "value": []
  }
]

Hey there @davidplane , thanks for posting!

Let’s discover what’s missing.

Alright, so the user you are testing the authorization has some role assigned👍🏼

We would also want to discover what properties are available under the session object (if the added claim can be reachable there) and if this can be printed out to the user this way.

Before we dig into that - could you please:

  • make sure the Action is deployed and added to the Flow?
  • the API that the user tries to authorize to have the RBAC feature enabled? This can be done via Auth0 dashboard → Applications → API → your API → Settings → toggle the switch of RBAC.

Could also try to verify if the claim is added to the token by decoding it via jwt.io - tokens should be available via the browser developer tool under the https://auth0_domain/oauth/token (response).

Looking forward to your reply!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.