3 Eylül 2023 Pazar

SpringSecurity JwtAuthenticationProvider Sınıfı

Giriş
Şu satırı dahil ederiz
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider;
Şeklen şöyle


Açıklaması şöyle
... Spring directs the incoming request to the right Authentication Provider (JwtAuthenticationProvider) through the AuthenticationManager. This provider is in charge of decoding and verifying the JWT access token. The provider then uses JwtAuthenticationConverter to turn the raw JWT into an AbstractAuthenticationToken. By default, it uses JwtGrantedAuthoritiesConverter at this step. The job of JwtGrantedAuthoritiesConverter is to change the incoming JWT into granted authorities.

By default, JwtGrantedAuthoritiesConverter splits the claim based on the “scope” or “scp” tags and turns it into a list of strings. After that, for each value, it adds the ‘SCOPE_’ prefix and creates a SimpleGrantedAuthority.
Örnek 
Şöyle yaparız
// Custom converter that splits based on the roles in the ‘roles’ claim 
// and fixing the prefix part.
private final class CustomJwtGrantedAuthoritiesConverter implements 
  Converter<Jwt, Collection<GrantedAuthority>> {

  @Override
  public Collection<GrantedAuthority> convert(Jwt jwt) {
    var realmAccess = (Map<String, List<String>>) jwt.getClaim("realm_access");

    return realmAccess.get("roles").stream()
      .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
      .collect(Collectors.toList());
    }

  @Override
  public <U> Converter<Jwt, U> andThen(Converter<? super Collection<GrantedAuthority>, ? extends U> after) {
    return Converter.super.andThen(after);
  }
}

// override the JwtAuthenticationConverter bean and set the // CustomJwtGrantedAuthoritiesConverter.
@Bean
public JwtAuthenticationConverter customJwtAuthenticationConverter() {
  JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
  converter.setJwtGrantedAuthoritiesConverter( new CustomJwtGrantedAuthoritiesConverter());
  return converter;
}

// give JwtAuthenticationConverter to the SecurityFilterChain.
@Bean
protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

  return http
    .csrf(AbstractHttpConfigurer::disable)
    .authorizeHttpRequests(requests ->
      requests
        .anyRequest().authenticated()
      )
      .oauth2ResourceServer(oauth2 ->
        oauth2.jwt(jwt ->
          jwt.jwtAuthenticationConverter(customJwtAuthenticationConverter())
        )
      )
      .build();
}



Hiç yorum yok:

Yorum Gönder