首页 > 解决方案 > 使用 JwkSetUri 向 NimbusJwtDecoder 进行身份验证失败

问题描述

我正在尝试使用 NimbusJwtDecoder.withJwkSetUri 设置资源服务器以使用身份验证服务器验证 jwt 令牌

以下是我在资源服务器中的配置

@Configuration
public class ResourceServerConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {

     http.oauth2ResourceServer(c -> {
        c.jwt(j -> {
           j.decoder(jwtDecoder());
        });
     });
     http.authorizeRequests().anyRequest().authenticated();
  }

  @Bean
  public JwtDecoder jwtDecoder(){
     RestTemplate rest = new RestTemplate();
     List<ClientHttpRequestInterceptor> interceptors = rest.getInterceptors();
     interceptors.add(new BasicAuthenticationInterceptor("client1","secret1"));
     interceptors.add(new LoggingInterceptor());
     rest.setInterceptors(interceptors);
     return NimbusJwtDecoder.withJwkSetUri("http://localhost:8080/oauth/token_key").restOperations(rest).build();
  }

}

我在资源服务器中有简单的端点来测试

@RestController
public class HelloController {

  @GetMapping("/hello")
    public String hello(){
    return "Hello";
  }
}

但是,当我使用已从身份验证服务器获得的访问令牌访问“/hello”时,我会收到未经授权的响应并在资源服务器中观察以下日志。

Response body: {"alg":"SHA256withRSA","value":"-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAo8ieQxTVHq4jBSM3JpO7UcFOa5UrorX5KhRbMqEtT746yGTqqv+t1EW6l8G31bGc6G/IHy7032vpKNxAgLVcoCrdoOakbGLb1y2+ElB9QmEEEplARWLQ43t47ywd0UA7MhF9WIbud1Z6kqySrsrBTzjPu+fwCElzUFveyaiPsZDlrEAU6yMLQ23nEP3bBCgDtGMVs1a7RsmAzfUsruelqNaAQQamobkjEMWB8ewZWjtsriIldNjGEAUznw4bcJ963ExtmgfMAHS7XhuWqu58yIzdBopxhZvt/falc5cyp7OCP1ZPEjkHJ5TikJksqOgDgWhiIVtr/3cUjd8vnX4y4QIDAQAB\n-----END PUBLIC KEY-----"}
2021-05-15 11:54:47.468 DEBUG 40223 --- [nio-9090-exec-3] o.s.web.client.RestTemplate              : Response 200 OK
2021-05-15 11:54:47.468 DEBUG 40223 --- [nio-9090-exec-3] o.s.s.o.s.r.a.JwtAuthenticationProvider  : Failed to authenticate since the JWT was invalid
2021-05-15 11:54:47.469 DEBUG 40223 --- [nio-9090-exec-3] w.c.HttpSessionSecurityContextRepository : Did not store empty SecurityContext
2021-05-15 11:54:47.469 DEBUG 40223 --- [nio-9090-exec-3] s.s.w.c.SecurityContextPersistenceFilter : Cleared SecurityContextHolder to complete request

似乎身份验证服务器能够成功提供公钥,但资源服务器无法使用此公钥来验证提供的 jwt 令牌。

非常感谢任何帮助。

标签: spring-bootspring-security-oauth2spring-oauth2

解决方案


嗨,请添加类 @EnableAuthorizationServer 注释但不起作用请阅读此 Outh2 文档https://projects.spring.io/spring-security-oauth/docs/oauth2.html


推荐阅读