spring-boot - 使用 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 令牌。
非常感谢任何帮助。
解决方案
嗨,请添加类 @EnableAuthorizationServer 注释但不起作用请阅读此 Outh2 文档https://projects.spring.io/spring-security-oauth/docs/oauth2.html
推荐阅读
- r-raster - 重新投影时 CRS 参数出错
- tensorflow - 如何在 tensorflow 2 (tf.keras) 中进行空洞卷积
- excel - 在特定位置使用 PowerShell 在 Excel 工作表中插入图像
- angular - 将 Angular 转换为 Angular Universal 时出错
- sql - 缺少数据部分通过带有excel vba的sql导入过滤后的文本文件数据
- r - R nls(); nlsModel 中的错误:初始参数估计处的奇异梯度矩阵
- shell - 将下载的文件移动到特定目录 - 为傻瓜做 inotify?
- java - 如何指示语法不在 ANTLR 侦听器中生成某些方法?
- javascript - 如何在javascript中添加&&到onclick和if函数?非常感谢
- html - 以下代码无法将输入的数据保存在 django 的数据库中