JWT with roles for Spring Security

If you’re already obtaining an access token that lists your API as one of the audiences then the likely cause for it to not include the information you expect is the rule implementation. More specifically, the correct way to add custom claims to the issued access token is to do something similar to;

function (user, context, callback) {
    const namespace = 'https://api.example.com/';

    context.accessToken[namespace + 'roles'] = "[your_roles_here]";

    callback(null, user, context);
}

The important parts are that you use context.accessToken to set your custom claims and that those same custom claims need to be namespaced (the namespace part is so that we ensure that there are no overlap between custom claims and OIDC claims; even future ones).

For reference information related to setting custom claims in issued tokens see:


Update:

It seems that JwtWebSecurityConfigurer will look at the scope claim to fill the authorities associated with the authenticated principal. Given that hasRole checks the authorities, but the actual role data is contained within a claim that was not used as source for the authorities then it fails.

The use of that library implies that the authorities will have to be available at the scope claim of the access token and then you can use hasAuthority to check for it. Note that this is my interpretation of how that library works; I might have missed some way to configure this, but I don’t think so as this issue suggests it needs to be the scope claim.