spring 5 - Oauth2服务器获得当前用户

问题描述 投票:0回答:1

我使用spring 5构建了一个Spring boot oauth2服务器.oauth服务器工作正常,我可以使用基本的auth和用户名/密码登录。我得到一个不记名令牌,我可以使用/ oauth / check_token网址验证令牌。

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

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

我启动postman以便我可以执行api调用,例如,调用/ oauth / token,我收到一个令牌。然后,我开始一个新请求,将身份验证方法设置为承载令牌并填写收到的承载令牌。我对url(http://localhost:8080/user)进行GET调用,结果证明校长始终为null。我知道因为我可以在Spring工具套件中调试我的应用程序而且Principal总是空的。我也尝试过:

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

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

spring spring-boot oauth-2.0
1个回答
0
投票

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

我有一个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安全性。

© www.soinside.com 2019 - 2024. All rights reserved.