【问题标题】:How do I get the right user principal with Spring-Boot and Oauth2?如何使用 Spring-Boot 和 Oauth2 获得正确的用户主体?
【发布时间】:2020-02-23 08:16:21
【问题描述】:

我正在练习 Spring-Boot 2.2 + Spring Security 5 + Oauth2。按照很多例子,我在这里碰壁了。

我的spring安全配置是这样的:

protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
      .antMatchers("/", "/css/**", "/webjars/**").permitAll()
      .anyRequest().authenticated()
      .and().oauth2Login().userInfoEndpoint()
      .userService(new DefaultOAuth2UserService());
}

我有一个使用这种方法的控制器:

@GetMapping("/create")
public ModelAndView create(Principal principal) {
    log.debug(principal);
    return new ModelAndView("create.html", "topicForm", new TopicForm());
}

在 Thymeleaf 模板中,我会调用 User,它只返回一个数字。

在debug中,authentication是org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken,Principal是DefaultOidcUser,name属性是“sub”,在google的oauth响应中不是名字而是数字。

DefaultOAuth2UserService 在控制器中的断点命中之前永远不会被调用。

我在哪里走错了路?

--编辑-- 在进一步调试中,我认为问题源于 OAuth2LoginAuthenticationFilter 调用 org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService 可以通过 oidcUserService(oidcUserService()) 进行配置

【问题讨论】:

    标签: spring-boot spring-security oauth-2.0


    【解决方案1】:

    要获取当前主体,您可以使用解析 Authentication.getPrincipal() 的 @AuthenticationPrincipal annotation,以便将其添加为参数。

    public ModelAndView create(@AuthenticationPrincipal Principal principal) {
        log.debug(principal);
        return new ModelAndView("create.html", "topicForm", new TopicForm());
    }
    

    【讨论】:

    • 它仍然是一个 OAuth2AuthenticationToken 并且没有调用 DefaultOAuth2UserService。另外,我需要在结果网页中的主体权限,在 thymeleaf 中我会调用 User,它只返回一个数字。
    【解决方案2】:

    您可以使用SecurityContextHolder。

    public ModelAndView create() {
        Object principal = SecurityContextHolder.getContext().getAuthentcation().getPrincipal();
        log.debug(principal);
        return new ModelAndView("create.html", "topicForm", new TopicForm());
    }
    

    【讨论】:

    • 这并没有改变主体不是我需要的类型这一事实。它是从 Google auth 返回的原始令牌,但我需要 DefaultOAuth2UserService 对其进行“改进”,以便稍后我从委托人那里得到我需要的东西。例如,在该控制器后面,我有一个 thymeleaf 模板,它使用 User 来检索经过身份验证的用户名。因为主体是原始令牌,所以所有标签返回的是一个 ID 号。
    猜你喜欢
    • 2021-07-22
    • 1970-01-01
    • 2019-05-18
    • 2018-01-05
    • 2023-04-06
    • 2019-01-09
    • 2016-11-03
    • 2019-07-09
    • 2019-08-01
    相关资源
    最近更新 更多