【问题标题】:Spring Cloud Gateway OAuth2 with Spring Security OAuth2 Authorization Server = loopSpring Cloud Gateway OAuth2 with Spring Security OAuth2 Authorization Server = loop
【发布时间】:2020-07-04 00:19:13
【问题描述】:

我正在尝试将 Spring Authorization Server 与 Spring Cloud Gateway 一起使用,但我一直无法获取用户信息。我可以在网关日志中看到类似

的消息

[2020-03-23 13:36:35,061] TRACE org.springframework.web.HttpLogging - [45961b04] Decoded [{access_token=5b5a13f1-2b47-4739-bda2-74785f6e3828, token_type=bearer, expires_in=33556, scope=read}]

这意味着授权工作正常,但在 302 FOUND Location: /res (protected resource) 之后它会将我转发回授权服务器。

完整代码在此处的演示项目中:https://github.com/looksworking/gw-oauth

授权服务器:

build.gradle.kts

application.yml

WebSecurityConfig

AuthZServerConfig

Spring Cloud 网关:

build.gradle.kts

application.yml

GatewayApplication

非常感谢任何帮助。

【问题讨论】:

    标签: spring spring-security oauth spring-security-oauth2 spring-cloud-gateway


    【解决方案1】:

    网关无法从授权服务器获取用户信息来创建主体。因此,由于缺少主体,它再次重定向到授权服务器。尝试在授权服务器中创建自定义用户信息端点。 (/userinfo 而不是 /oauth/userinfo)。您可能需要在安全配置中允许 /userinfo。

    @RestController
    public class UserInfoEndpoint {
    
        @PostMapping("/userinfo")
        public Map<String, Object> user() {
            Map<String, Object> map = new HashMap<>();
            String name = SecurityContextHolder.getContext().getAuthentication().getName();
            map.put("user_name", name);
            return map;
        }
    
    }
    

    另外,将 user-info-authentication-method: form 添加到您的提供商。

    【讨论】:

    • 你绝对是对的——我错过了那个端点,我添加了它,我还在项目中添加了 UAA 服务器,这样我就可以从 100% 工作的 oauth 服务器切换到我的。当我切换到 UAA 时,我可以在日志中看到网关将 GET 到 /userinfo。我添加了这个端点,但我仍然得到这个循环,当我切换到我的授权服务器时,我没有在日志中看到任何 /userinfo 请求。相应地更新了 github 项目。
    • 首先,让我们确保将 gw-oauth-auth 添加到本地 dns (/etc/host)。如果没有,请在网关提供商 yml 中使用 172.10.16.1 更改它们。其次,您在身份验证服务器中创建了端点。它在地图中返回“user_name”,但您在网关中设置了“user-name-attribute: sub”。在 auth 的 return 语句中更改为 user_name 或更改 sub。此外,您不需要提供程序中的 check-token-uri 和 jwk-set-uri 属性。多一个。您的重定向 uri 缺少注册 ID。设置为重定向 uri:“{baseUrl}/login/oauth2/code/{registrationId}”。
    • 是的,在尝试一切的时候有点搞砸了名字,在我的情况下,你说的主要原因是正确的——redirect-uri 中没有注册 ID。非常感谢您的宝贵时间!
    猜你喜欢
    • 2019-04-29
    • 2021-10-20
    • 2020-06-20
    • 2022-11-08
    • 2021-03-16
    • 2019-09-25
    • 2019-04-06
    • 2019-01-09
    • 2022-01-02
    相关资源
    最近更新 更多