Giriş
Şu satırı dahil ederiz
Şu satırı dahil ederiz
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationProvider;
Şeklen şöyle
Açıklaması şöyle
Örnek... 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.
Şöyle yaparız
// Custom converter that splits based on the roles in the ‘roles’ claim// and fixing the prefix part.private final class CustomJwtGrantedAuthoritiesConverter implementsConverter<Jwt, Collection<GrantedAuthority>> {@Overridepublic 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());}@Overridepublic <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.@Beanpublic JwtAuthenticationConverter customJwtAuthenticationConverter() {JwtAuthenticationConverter converter = new JwtAuthenticationConverter();converter.setJwtGrantedAuthoritiesConverter( new CustomJwtGrantedAuthoritiesConverter());return converter;}// give JwtAuthenticationConverter to the SecurityFilterChain.@Beanprotected 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