【问题标题】:spring 5 - Oauth2 server get current userspring 5 - Oauth2 服务器获取当前用户
【发布时间】:2019-01-12 14:45:28
【问题描述】:

我已经使用 spring 5 构建了一个 Spring boot oauth2 服务器。oauth 服务器工作,我可以使用基本身份验证和用户名/密码登录。我得到一个不记名令牌,我可以使用 /oauth/check_token url 验证令牌。

在同一个 Spring boot 项目中,我想添加一个端点,该端点将打印出经过身份验证的用户信息,以便 oauth2 客户端可以通过登录用户获取信息。我创建了一个端点 /user,它看起来像这样:

@GetMapping("/user")
@ResponseBody
public Principal user(Principal user) {
    return user;
}

我启动邮递员,以便我可以进行 api 调用等,调用 /oauth/token 并收到一个令牌。然后我开始一个新的请求,将身份验证方法设置为不记名令牌并填写接收到的不记名令牌。我对 url (http://localhost:8080/user) 进行了 GET 调用,结果发现主体始终为空。我知道,因为我可以在 Spring 工具套件中调试我的应用程序,而 Principal 始终为空。我也试过:

OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)SecurityContextHolder.getContext() .getAuthentication();

那也是空的。如何创建将打印用户信息的端点,以便客户端可以设置 userInfoUri 属性。

【问题讨论】:

  • 您能否将完整的请求详细信息分享给 /users。

标签: spring spring-boot oauth-2.0


【解决方案1】:

我有答案。我会在这里发布,以防其他人遇到这个问题。

我有一个 ResourceServerConfigurerAdapter,其中包含以下配置:

public void configure(HttpSecurity http) throws Exception {
    http.anonymous()
        .disable()
        .requestMatchers()
        .antMatchers("/api/user/**").and().authorizeRequests()
        .antMatchers("/user").authenticated()
        // More rules here

因为第一个 antMatchers("/api/user/**") 它没有工作的原因。我改成这样:

http.anonymous()
    .disable()
    .requestMatchers()
    .antMatchers("**").and().authorizeRequests()

我相信第一个 antMatchers 确定它强制授权的路径(在该路径中启用 oauth2 安全性)所以如果第一个路径是 .antMatchers("/api/user/**") 之后是 .antMatchers( "/user") 那么它将不匹配并且 /user url 不会启用 oauth2 安全性。

【讨论】:

    猜你喜欢
    • 2018-08-17
    • 2018-06-16
    • 2014-10-27
    • 2015-09-12
    • 2020-11-23
    • 2019-02-02
    • 2016-05-06
    • 1970-01-01
    • 2020-07-23
    相关资源
    最近更新 更多