【问题标题】:Failed to authenticate with NimbusJwtDecoder withJwkSetUri使用 JwkSetUri 向 NimbusJwtDecoder 进行身份验证失败
【发布时间】:2021-08-05 07:39:36
【问题描述】:

我正在尝试使用 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-boot spring-security-oauth2 spring-oauth2


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 2018-11-02
    • 1970-01-01
    • 2016-06-28
    • 2019-05-29
    • 2020-10-30
    • 1970-01-01
    相关资源
    最近更新 更多