23 Ağustos 2022 Salı

SpringSecurity OAuth2 ResourceServerConfigurerAdapter Sınıfı - Kendi OAuth2 Resource Sunucumuz İçin

Örnek
Şöyle yaparız
@EnableWebSecurity
public class OAuth2ResourceServerSecurityConfiguration {


  @Value("${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}")
  private String jwkSetUri;

  @Value("${spring.security.oauth2.resourceserver.jwt.jws-algorithm}")
  private String jwsAlgorithm;

  private static final String COUNTRIES_RESOURCE_PATH = "countries";

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

    http
      .authorizeHttpRequests((authorize) -> authorize
        .mvcMatchers(HttpMethod.GET, "/" + COUNTRIES_RESOURCE_PATH + "/**")
        .hasAnyRole(Role.MANAGER.getValue(), Role.USER.getValue())
        .mvcMatchers(HttpMethod.POST, "/" + COUNTRIES_RESOURCE_PATH + "/**")
        .hasAnyRole(Role.MANAGER.getValue())
        .mvcMatchers(HttpMethod.PUT, "/" + COUNTRIES_RESOURCE_PATH + "/**")
        .hasAnyRole(Role.MANAGER.getValue())
        .mvcMatchers(HttpMethod.DELETE, "/" + COUNTRIES_RESOURCE_PATH + "/**")
        .hasAnyRole(Role.MANAGER.getValue())
        .anyRequest().authenticated()
      ).sessionManagement(config -> config.sessionCreationPolicy(SessionCreationPolicy.STATELESS)).csrf().disable()
      .oauth2ResourceServer((oauth2) -> oauth2.jwt(
        jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())));

    return http.build();
  }

  @Bean
  public JwtDecoder jwtDecoder() {
    return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
        .jwsAlgorithm(SignatureAlgorithm.from(jwsAlgorithm)).build();
  }

  private Converter<Jwt, ? extends AbstractAuthenticationToken> jwtAuthenticationConverter() {
    JwtAuthenticationConverter jwtConverter = new JwtAuthenticationConverter();
    jwtConverter.setJwtGrantedAuthoritiesConverter(new ResourceRoleConverter());
    return jwtConverter;
  }
}
ResourceRoleConverter şöyle
public class ResourceRoleConverter implements Converter<Jwt, Collection<GrantedAuthority>> {
private static final Logger LOG = LoggerFactory.getLogger(ResourceRoleConverter.class); private static final String REALM_ACCESS = "realm_access"; private static final String ROLES = "roles"; @Override public Collection<GrantedAuthority> convert(Jwt jwt) { try { List<String> roles = JSONObjectUtils.getStringList((Map<String, Object>) jwt.getClaims().get(REALM_ACCESS),ROLES); return roles.stream() .map(roleName -> "ROLE_" + roleName) .map(SimpleGrantedAuthority::new) .collect(Collectors.toList()); } catch (ParseException e) { LOG.error(e.getMessage(),e); throw new RuntimeException("Error while trying to get user roles"); } } }


Hiç yorum yok:

Yorum Gönder