首页 > 解决方案 > 我可以将 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'

谢谢

标签: javaspring-bootjwtspring-security-oauth2

解决方案


经过一天的谷歌搜索,我实际上找到了一个解决方案:

  1. 令牌在 @RegisteredOAuth2AuthorizedClient OAuth2AuthorizedClient 客户端中可用,并且可以注入控制器方法
  2. 我的令牌转发/委托/模拟案例在这里描述:https ://spring.io/blog/2018/03/06/using-spring-security-5-to-integrate-with-oauth-2-secured-services -例如 facebook 和 github

所描述的解决方案确实适用于我的情况。


推荐阅读