How to parse roles put in custom claims in Spring Security?

Hi there, I’m using the Authorization extension and I created a rule to put the groups and roles of a user into a custom claim in the access token for my API, under “[namespace]/groups” and “[namespace]/roles” respectively. That works just fine.

However, I’m trying to figure out how to integrate that with Spring Security. I looked at this link: JWT with roles for Spring Security

It’s outdated and references the old Auth0 Spring SDK, but I’m going to assume it’s still accurate in the idea that Spring looks at the “scope” attribute of the JWT and parses groups/roles/permissions from there.

If so, does that mean I will have to manually go through the groups and roles I put in the access token and put them into the scope field instead? If so, how would I go about doing that effectively? If not, what is a viable way?

I created a rule to flatten the groups and roles and put them into the scope field:

function (user, context, callback) {
    let user_groups = user.groups;
    let user_roles = user.roles;
    let customScope = "openid profile email";
    if(user_groups !== null && user_groups.length > 0) {
        for (let i = 0; i < user_groups.length; i++) {
            customScope += " " + user_groups[i];
        }  
    }

    if(user_roles !== null && user_roles.length > 0) {
        for (let i = 0; i < user_roles.length; i++) {
            customScope += " " + user_roles[i];
        }    
    }

    context.accessToken.scope = customScope;

    return callback(null, user, context);
}

And then in the SecurityConfig class, I have:

http.authorizeRequests().mvcMatchers("/auth0endpoint").hasAuthority("SCOPE_[name of group/role]")
            .and()
            .oauth2ResourceServer().jwt();

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