简体   繁体   中英

Can't access OAuth2AuthenticationToken when using Google OAuth2 in Spring Boot

I am trying to implement logging in with google into my Spring Boot app with a custom defaultSuccessUrl . The authentication seems to go through but when I get to the success url endpoint I can't get the OAuth2AuthenticationToken (it is null if put as an argument of the method) and when I fetch the authentication from the security context it comes back as AnonymousAuthenticationToken as such: 在此处输入图像描述

I have these dependencies added:

        <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>

Here is my 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);
    }

And here is the success endpoint:


@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";
    }

}

It redirects to the endpoint properly but the OAuth2AuthenticationToken is null and as I said before the authentication held in the security context is AnonymousAuthentication. Where is the problem of not providing proper Authentication objects?

I have the same issue and my solution is not 100% perfect but it works. You can remove

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

With SessionCreationPolicy.STATELESS after successful login you will be only forwarded to your defaultSuccessUrl as an Anonymous (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'

but if you remove STATELESS then your object will be set OAuth2AuthenticationToken authentication and in the log, you will see a different output with 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM