如何配置 Reactive Resource Server 以使用带有对称密钥的 JWT?

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

在授权服务器上,我的 Jwt 是这样生成的:

      @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;
      }

现在在 Reactive Resource 服务器端:

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

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

在给定签名密钥的情况下,如何配置我的 Reactive Resource Server 使用该令牌?

  @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();
 }

除非您指定签名算法,否则授权服务器使用 HMACSHA256 作为默认算法。所以你需要在资源服务器配置中指定这个。