简体   繁体   中英

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 ?

  @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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM