java 在Sping Boot 中使用Google OAuth2时无法访问OAuth2AuthenticationToken

slsn1g29  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(188)

我尝试使用自定义defaultSuccessUrl实现Google登录到我的Sping Boot 应用程序中。身份验证似乎通过了,但当我到达success url端点时,我无法获得OAuth2AuthenticationToken(如果作为方法的参数,则为null),当我从安全上下文获取身份验证时,它返回为AnonymousAuthenticationToken:

我添加了这些依赖项:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-oauth2-jose</artifactId>
        </dependency>

下面是我的SecurityConfig:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .mvcMatchers("/api/users/login").permitAll()
                .requestMatchers(EndpointRequest.toAnyEndpoint()).authenticated()
                .antMatchers("/api/users/login**","/callback/", "/webjars/**", "/error**").permitAll()
                .antMatchers("/oauth_login", "/loginFailure", "/").permitAll()
                .anyRequest().authenticated()
                .and()
                .oauth2Login()
                .defaultSuccessUrl("/api/users/loginSuccess", true)
                .failureUrl("/loginFailure");

        http.csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

这里是成功的终点:

@RestController
@RequestMapping("/api/users")
@RequiredArgsConstructor
public class UserController {

    private final OAuth2AuthorizedClientService authorizedClientService;

    @GetMapping("/loginSuccess")
    public String getLoginInfo(Model model, OAuth2AuthenticationToken authentication) {
        OAuth2AuthorizedClient client = authorizedClientService
                .loadAuthorizedClient(authentication.getAuthorizedClientRegistrationId(), authentication.getName());

        String userInfoEndpointUri = client.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri();

        if (!StringUtils.isEmpty(userInfoEndpointUri)) {
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + client.getAccessToken().getTokenValue());
            HttpEntity entity = new HttpEntity("", headers);

            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Map> response = restTemplate.exchange(userInfoEndpointUri, HttpMethod.GET, entity, Map.class);
            Map userAttributes = response.getBody();

            model.addAttribute("name", userAttributes.get("name"));
        }

        return "loginSuccess";
    }

}

它正确地重定向到端点,但是OAuth2AuthenticationToken为null,并且正如我之前所说的,安全上下文中的身份验证是AnonymousAuthentication。

nmpmafwu

nmpmafwu1#

我有同样的问题,我的解决方案不是100%完美,但它的工作原理。你可以删除

http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

使用SessionCreationPolicy.STATELESS成功登录后,您将仅以匿名身份转发到您的defaultSuccessUrl(ROLE_ANONYMOUS)

o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@41c9a549
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
.....
o.s.s.w.a.AnonymousAuthenticationFilter  : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken@1c19acdf: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@43458: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: ......................; Granted Authorities: ROLE_ANONYMOUS'

但如果删除STATELESS,则对象将被设置为OAuth2AuthenticationToken authentication,并且在日志中,您将看到ROLE_USER的不同输出

o.s.s.w.header.writers.HstsHeaderWriter  : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher@274a9530
w.c.HttpSessionSecurityContextRepository : SecurityContext 'org.springframework.security.core.context.SecurityContextImpl@ffb235ff: Authentication: org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken@ffb235ff: Principal: Name: [111026035798596971137], Granted Authorities: [[ROLE_USER, SCOPE_https://www.googleapis.com/auth/userinfo.email, SCOPE_https://www.googleapis.com/auth/userinfo.profile, SCOPE_openid]], User Attributes: [{at_hash=lRLZ7qJohqoHD5EiCjufeA, sub=111026035798596971137, email_verified=true, iss=https://accounts.google.com, given_name=Andrzej, locale=pl, nonce=-................-W3M, picture=https://lh5.googleusercontent.com/-5vFrrro_VtI/AAAAAAAAAAI/AAAAAAAAAAA/...........-_A/s96-c/photo.jpg, aud=[.........-................apps.googleusercontent.com], azp=...-...........apps.googleusercontent.com, name=Andrzej ..., hd=.....pl, exp=2020-04-27T14:54:48Z, family_name=......, iat=2020-04-27T13:54:48Z, email=a.....@.....pl}]; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: ...............; Granted Authorities: ROLE_USER, SCOPE_https://www.googleapis.com/auth/userinfo.email, SCOPE_https://www.googleapis.com/auth/userinfo.profile, SCOPE_openid' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade@7bfa86bb
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
.....
o.s.s.w.a.AnonymousAuthenticationFilter  : SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken@ffb235ff: Principal: Name: [............], Granted Authorities: [[ROLE_USER, SCOPE_https://www.googleapis.com/auth/userinfo.email, SCOPE_https://www.googleapis.com/auth/userinfo.profile, SCOPE_openid]], User Attributes: [{at_hash=........., sub=............, email_verified=true, iss=https://accounts.google.com, given_name=Andrzej, locale=pl, nonce=-...............-W3M, picture=https://lh5.googleusercontent.com/-5vFrrro_VtI/..........-_A/s96-c/photo.jpg, aud=[.....-............apps.googleusercontent.com], azp=224074472498-................apps.googleusercontent.com, name=Andrzej ....., hd=....pl, exp=2020-04-27T14:54:48Z, family_name=.............., iat=2020-04-27T13:54:48Z, email=a..........@.....pl}]; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails@380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: ...........; Granted Authorities: ROLE_USER, SCOPE_https://www.googleapis.com/auth/userinfo.email, SCOPE_https://www.googleapis.com/auth/userinfo.profile, SCOPE_openid'

相关问题