acmoune
acmoune

Reputation: 3433

How to configure a Reactive Resource Server to use a JWT with a symmetric key?

On the Authorization server, my Jwt was generated with this:

      @Value("${jwt.key}")
      private String jwtKey;

      @Override
      public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
            .authenticationManager(authenticationManager)
            .tokenStore(tokenStore)
            .accessTokenConverter(jwtAccessTokenConverter);
      }
    
      @Bean
      public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
      }
    
      @Bean
      public JwtAccessTokenConverter jwtAccessTokenConverter() {
        var converter = new JwtAccessTokenConverter();
        converter.setSigningKey(jwtKey);
        return converter;
      }

Now on the Reactive Resource server side:

  @Value("${jwt.key}")
  private String jwtKey;

  @Bean
  public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
    return http
        .authorizeExchange()
        .anyExchange().authenticated()
        .and()
        .oauth2ResourceServer()
        .jwt(jwtSpec -> {...})
        .and.build();
  }

How can I configure my Reactive Resource Server to use that token, given the signing key ?

Upvotes: 1

Views: 3890

Answers (1)

denizg
denizg

Reputation: 952

  @Value("${jwt.key}")
  private String jwtKey;

  @Bean
  public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
    return http
        .authorizeExchange()
        .anyExchange().authenticated()
        .and()
        .oauth2ResourceServer()
        .jwt(jwtSpec -> { jwtSpec.decoder(jwtDecoder()); })
        .and.build();
  }

  @Bean
  public JwtDecoder jwtDecoder() {
    SecretKey secretKey = new SecretKeySpec(jwtKey, "HMACSHA256");
    return NimbusJwtDecoder
            .withSecretKey(secretKey)
            .macAlgorithm(MacAlgorithm.HS256)
            .build();
 }

Unless you specify sign algorithm, authorization server uses HMACSHA256 as default algorithm. So you need to specify this in resource server config.

Upvotes: 3

Related Questions