getSession not retrieving the roles after signing up

auth0 getSession/useUser returns empty role array after signing up a user.

When the user doesn’t exist and they sign up, they get assigned a default role in Auth0 dashboard, BUT, getSession or useUser doesn’t get the roles UNLESS, the user re-logins.

If I logout after signing up, then log in, getSession retrieves the roles without a problem.

exports.onExecutePostLogin = async (event, api) => {
const namespace = “role”;

if (event.authorization) {
api.idToken.setCustomClaim(${namespace}, event.authorization.roles);
api.accessToken.setCustomClaim(${namespace}, event.authorization.roles);
}
};

This is how I set roles as custom claims on Login and then retrieve them with getSession OR useUser in my NextJS App.

How do i make it so that when the user signs up, the roles that are being set also get retrieved instead of an empty array?

Hey there @tsintsabadzevano welcome to the community!

Can you help me understand this functionality a bit better? How exactly is the role being added on registration? Is this done in another Action?

Hello, thank you for replying.

Yes. The default roles are being assigned using an action on Login.

exports.onExecutePostLogin = async (event, api) => {
if (event.authorization && event.authorization.roles && event.authorization.roles.length === 0) {
const ManagementClient = require(“auth0”).ManagementClient;
const management = new ManagementClient({
domain: event.secrets.domain,
clientId: event.secrets.clientId,
clientSecret: event.secrets.clientSecret,
});

const params = {id: event.user.user_id};
const data = {“roles”: [“rol_37wxXWucoteCFyfk”]};

try {
await management.users.assignRoles(params,data)
} catch (err) {
console.log(err);
}

}

};

You need to check if its first login then assign the role in auth0, but when you are assign it in the access token as custom claim just hardcode the name of the role. In all requests after that you just take it from event.authorization.roles

1 Like

however I always prefer to construct the the custom claims in our system, so in post login action I am just making a call to our services to get the custom claims needed in the user’s token. Main reason for this is the mngmnt api rate limit on auth0. For example imagine if you have 1000 users registering in same time, which means you will hit the auth0 mngmnt api 1000 times for assigning the role, plus potential other requests if you assign custom data in app_metadata, which will results with issue because of the rate limit.

1 Like