java - 我可以将 JWT 授权从 spring RestController 传递给外部后端 API
问题描述
我有一个带有非常简单的 jQuery 页面作为前端的 spring boot BFF。BFF 需要带有外部授权服务器的 OAUTH2。(不确定 BFF 在这里是否真的是正确的术语,但我希望我的意思足够清楚)
登录和授权后,我想调用由同一授权服务器保护的 REST API,我需要登录时的用户凭据 (JWT)。
FE -> BFF -> 外部 API
如何在 BFF REST 控制器中传递这些凭据?
我找到了从请求标头中获取令牌并将其手动添加到后端调用请求的建议。但在我的情况下,Spring 使用基于会话的安全性,并且令牌既不在标头中,也不在主体中,也不在会话中。(我可能会强制 Spring 使用无状态安全性,但这种方法似乎值得怀疑)
我这样做完全错了吗?
这就是我想做的:
@GetMapping("/fromApi")
public String getValueFromApi(){
RestTemplate api = new RestTemplate();
// this call needs to have the "Authorization: Bearer token" header set
Map response = api.getForObject("https://secure.backend.api/giveme", Map.class);
// will throw: org.springframework.web.client.HttpClientErrorException$Unauthorized: 401 Unauthorized: [{"error":"authorization not provided"}]
return "Entries: " + response.size();
}
这些是我的依赖项:
implementation 'org.webjars:jquery:3.4.1'
implementation 'org.webjars:bootstrap:4.3.1'
implementation 'org.webjars:webjars-locator-core'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
谢谢
解决方案
经过一天的谷歌搜索,我实际上找到了一个解决方案:
- 令牌在 @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient 客户端中可用,并且可以注入控制器方法
- 我的令牌转发/委托/模拟案例在这里描述:https ://spring.io/blog/2018/03/06/using-spring-security-5-to-integrate-with-oauth-2-secured-services -例如 facebook 和 github
所描述的解决方案确实适用于我的情况。
推荐阅读
- tensorflow - jupyter中的张量板窗口大小
- java - Java寻宝游戏
- javascript - 如何将 Javascript 变量(包含 XML)的内容保存到本地磁盘?
- java - JavaFx - 在“InnerScenes”和 RootScene 之间切换
- tslint - Tslint 强制用于访问修饰符和函数之间的空间
- android - 程序类型已经存在:android.support.annotation.AnimRes
- r - 添加黑色轮廓 geom_point 并填充与其他不同的自变量
- spring-boot - 在 GCP Compute Engine 上的 spring-boot 应用程序中获取“ssl3_get_record:wrong version number”
- mule - “何时和其他”条件的问题
- python - 如何使用 2 个 pandas DataFrames 计算 IOU(重叠)