Spring Security: extract oidc role claims to spring authorities

Viewed 1267

I am trying to get role claims from an OAuth2AuthenticationToken to be detected as Spring Security authorities. There is a custom role defined on OIDC provider side (Azure AD in my case) that is nested inside the DefaultOidcUser, but not added automatically to the authorities: enter image description here

I tried to extract them from the Jwt Token like this

However, when I do that, neither of the following methods is called (neither during login, nor later, even in the default configuration):

  • JwtGrantedAuthoritiesConverter.convert(Jwt)
  • JwtAuthenticationConverter.convert(Jwt)
  • JwtAuthenticationConverter.extractAuthorities(Jwt)

My current configuration is:

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@Import(SecurityProblemSupport.class)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Override
    public void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
            .csrf()
            <some more config that has nothing to do with oauth/oidc>
            .and()
            .oauth2Login()
            .and()
            .oauth2ResourceServer()
            .jwt()
            .jwtAuthenticationConverter(jwtAuthenticationConverter())
            .and()
            .and()
            .oauth2Client()
        ;
    }

    private JwtAuthenticationConverter jwtAuthenticationConverter() {
        // create a custom JWT converter to map the roles from the token as granted authorities
        JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
        jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName("roles");     
        JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
        jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
        return jwtAuthenticationConverter;
    }
}

I also tried with a

CustomJwtAuthConverter implements Converter<Jwt, AbstractAuthenticationToken>

but to no avail.

Any help would be appreciated.

1 Answers

Managed to achieve it using an authorities mapper that also extracts claims from the oidcToken:

public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    
    [...]
   
    @Bean
    public GrantedAuthoritiesMapper userAuthoritiesMapper() {
        return authorities -> {
            Set<GrantedAuthority> mappedAuthorities = new HashSet<>();

            authorities.forEach(
                authority -> {
                    // Check for OidcUserAuthority because Spring Security 5.2 returns
                    // each scope as a GrantedAuthority, which we don't care about.
                    if (authority instanceof OidcUserAuthority) {
                        OidcUserAuthority oidcUserAuthority = (OidcUserAuthority) authority;
                        mappedAuthorities.addAll(SecurityUtils.extractAuthorityFromClaims(oidcUserAuthority.getUserInfo().getClaims()));
                        mappedAuthorities.addAll(SecurityUtils.extractAuthorityFromClaims(oidcUserAuthority.getIdToken().getClaims()));
                    }
                }
            );
            return mappedAuthorities;
        };
    }

}

and inside SecurityUtils:

public static List<GrantedAuthority> extractAuthorityFromClaims(Map<String, Object> claims) {
        return mapRolesToGrantedAuthorities(getRolesFromClaims(claims));
    }
private static List<GrantedAuthority> mapRolesToGrantedAuthorities(Collection<String> roles) {
        return roles.stream().filter(role -> role.startsWith("ROLE_")).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

Afterwards the custom role should be present in mappedAuthorities and with it in the authorities of the token. Thus making the annotations "hasRole" and "hasAuthority" possible to use.

Related