WEB/Security

Lesson 26 - Endpoint authorization rules for an OAuth 2 resource server

Tony Lim 2022. 5. 14. 15:59
728x90

401 -> authentication issue

403 -> forbidden , authorization issue


@Configuration
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http.oauth2ResourceServer(
            c -> c.jwt(
                    j -> j.decoder(decoder())
                    .jwtAuthenticationConverter(converter())
            )
    );

    http.authorizeRequests()
            .mvcMatchers("/demo/**").hasAuthority("read");
  }

  @Bean
  public JwtDecoder decoder() {
    String key = "ymLTU8rq83j4fmJZj60wh4OrMNuntIj4fmJ";
    SecretKey secretKey = new SecretKeySpec(key.getBytes(),0 ,key.getBytes().length, "AES");
    return NimbusJwtDecoder.withSecretKey(secretKey)
            .build();
  }

  @Bean
  public JwtAuthenticationConverter converter() {
    var conv = new JwtAuthenticationConverter();
    conv.setJwtGrantedAuthoritiesConverter(jwt -> {
      JSONArray a = (JSONArray) jwt.getClaims().get("authorities");
      return a.stream()
              .map(String::valueOf)
              .map(SimpleGrantedAuthority::new)
              .collect(Collectors.toList());
    });
    return conv;
  }


}

need to specify converter or resource server will not be able to extract GrantedAuthorites

 

 

728x90