Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create custom claims in JWT using spring-authorization-server

I'm building an OAuth2 authorization server based on the experimental Spring project Spring Authorization Server

My use case is quite simple, fetch users from a DB, and based on some properties of the user, set some custom claims in the JWT being produced. I haven't found a way to do so with Spring Authorization Server, the only way I could work out is to inject a jwtCustomizer object as part of the JwtEncoder bean definition:

  @Bean
  public JwtEncoder jwtEncoder(CryptoKeySource keySource) {
    NimbusJwsEncoder jwtEncoder = new NimbusJwsEncoder(keySource);
    jwtEncoder.setJwtCustomizer((headersBuilder, claimsBuilder) -> {
      // Inject some headers and claims...
    });
    return jwtEncoder;
  }

This obviously doesn't give me access to users information, therefore I can't set the claims I need at this point. Did anyone manage to solve this problem?

like image 283
Nick Melis Avatar asked Jan 11 '21 16:01

Nick Melis


People also ask

How does JWT work with Spring Security?

We expose a public POST API for the authentication, and upon passing the correct credentials, it will generate a JWT. If a user tries to access the protected API, it will allow access only if a request has a valid JWT. Validation will happen in the filter registered in the Spring Security filter chain.

What is JWT Sub claim?

Use of this claim is OPTIONAL. 4.1.2. " sub" (Subject) Claim The "sub" (subject) claim identifies the principal that is the subject of the JWT. The claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique.


1 Answers

The solution for this is in a test of the library

    @Bean
    OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer() {
        return context -> {
            if (context.getTokenType().getValue().equals(OidcParameterNames.ID_TOKEN)) {
                Authentication principal = context.getPrincipal();
                Set<String> authorities = principal.getAuthorities().stream()
                        .map(GrantedAuthority::getAuthority)
                        .collect(Collectors.toSet());
                context.getClaims().claim(AUTHORITIES_CLAIM, authorities);
            }
        };
    }
like image 95
Yunier Broche Guevara Avatar answered Oct 23 '22 15:10

Yunier Broche Guevara