reactjsauth0

Get roles of user with Auth0 and React


I can't seem to retrieve the roles of a User in my frontend. Token Claims Log doesn't give me any info that the post-login trigger worked and Roles log gives me undefined.

I try to get them with this:

useEffect(() = {
    const fetchUserRole = async () = {
    if (isAuthenticated) {
        try {
            const claims = await getIdTokenClaims();
            console.log("Token Claims:", claims); // Debugging

                if (claims) {
                    const roles = claims[`${namespace}/claims/roles`];
                    console.log("Roles:", roles);

                    if (roles && roles.length > 0) {
                        setRole(roles[0]);
                    }
                }
            } catch (error) {
                console.error("Error fetching role:", error);
            }
        }
    };

    fetchUserRole();
}, [isAuthenticated, getIdTokenClaims]);

I created a trigger to append the roles. I believe in the past you needed to do this with rules but I didn't find them in my dashboard.

enter image description here

This is the custom code to add the roles to the token id:

exports.onExecutePostLogin = async (event, api) => {
    const namespace = "https://dev-<my-domain>.eu.auth0.com/claims"; // I replaced it with my domain
    console.log("Auth0 Event Data:", JSON.stringify(event, null, 2));

    if (event.authorization && event.authorization.roles.length > 0) {
        console.log("Roles found:", event.authorization.roles);

        api.idToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
        api.accessToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
    } else {
        console.log("No roles assigned to this user.");
    }
};

Solution

  • I managed to find the error.

    Auth0 enforces namespacing for custom claims in tokens to avoid conflicts with standard OpenID Connect (OIDC) claims (like sub, email, name). If you want to include custom attributes (like user roles), you must prefix them with a unique, non-Auth0 domain.

    I used my auth0 domain which lead to the trigger not working. After changing the namespace to a custom one it worked properly.