Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/spring-boot/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring boot 如何使用Spring Boot和Oauth2获得正确的用户主体?_Spring Boot_Spring Security_Oauth 2.0 - Fatal编程技术网

Spring boot 如何使用Spring Boot和Oauth2获得正确的用户主体?

Spring boot 如何使用Spring Boot和Oauth2获得正确的用户主体?,spring-boot,spring-security,oauth-2.0,Spring Boot,Spring Security,Oauth 2.0,我正在练习Spring Boot 2.2+Spring Security 5+Oauth2。下面是很多例子,我在这里遇到了麻烦 我的spring安全配置如下: protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/", "/css/**", "/webjars/**").permitAll() .anyReques

我正在练习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,它只返回一个数字

在调试中,身份验证是org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken,主体是DefaultOidcUser,name属性是“sub”,它不是名称,而是google oauth响应中的数字

DefaultOAuth2UserService在我的断点到达控制器之前从未调用过

我在哪里拐错了弯

--编辑--
在进一步调试中,我认为问题源于OAuth2LoginAuthenticationFilter调用org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService,这将由OidcUserService(OidcUserService())配置

要获取当前主体,您可以使用
@AuthenticationPrincipal annotation
,它解析
身份验证.getPrincipal()
,以便将其添加为参数

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

您可以使用
SecurityContextHolder

公共模型和视图创建(){ 对象主体=SecurityContextHolder.getContext().GetAuthentication().getPrincipal(); log.debug(主体); 返回新的ModelAndView(“create.html”、“topicForm”、newtopicform()); }
它仍然是一个OAuth2AuthenticationToken,并且未调用DefaultOAuth2UserService。此外,我需要在生成的网页中使用principal权限,在thymeleaf中我将调用User,它只返回一个数字。这不会改变principal不是我需要的类型的事实。这是从GoogleAuth返回的原始令牌,但我需要DefaultOAuth2UserService对其进行“细化”,以便稍后从主体处获得所需的内容。例如,在该控制器后面,我有一个thymeleaf模板,它使用User来检索经过身份验证的用户名。因为主体是原始标记,所以所有标记返回的都是ID号。