Create custom claim on role level

Is it possible to create a custom claim included in the access token for all users who have a specific role assigned? I.e., I’d not like to define the content of the claim for individual users who have that role (because the claim content is identical for all these users), but for the role. Then add it to the access token in a post-login action.

Is it possible to realize such thing with the Authentication Core (without the extension)?

Hi @jochen.walz,

Yes, it is possible to add a custom claim to the access token if they have a specific role assigned.

Something like the following could work:

exports.onExecutePostLogin = async (event, api) => {
const namespace = 'https://myapp.example.com';
if (event.authorization.roles.includes('admin'))) {
    // Set claims in access token
    api.accessToken.setCustomClaim(`${namespace}/role`, "admin");
  }
};

Reference: Adding custom claims to tokens

Let me know if there’s anything else I can do to help.

Thanks,
Rueben

1 Like

Thanks Rueben!

Depending on how much granularity we must provide, we may end up with a longer list of if-else-if-else-… (or a switch). I had hoped for some option to define the content of the claim on role level which I just haven’t found yet and have a one-liner to add it to the token in the action. But obviously that’s what it is.

1 Like

Hi @jochen.walz,

Yes, that would work with a longer list of if-else statements or a switch.

Unfortunately, there isn’t an option to define the content at the role level. Only permissions can be defined at the Role level. Perhaps you could leverage that if it works for your use case.

If you decide to use permissions, you can toggle on a feature in your API settings to Add Permissions in the Access Token.

I hope this helps!

Let me know if you have any further questions.

Cheers,
Rueben

1 Like

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