Я пытаюсь выполнить вход с помощью Google в мое приложение Spring Boot с пользовательским defaultSuccessUrl
. Кажется, аутентификация проходит, но когда я добираюсь до конечной точки URL-адреса успеха, я не могу получить OAuth2AuthenticationToken (это значение равно null, если он указан в качестве аргумента метода), и когда я получаю аутентификацию из контекста безопасности, он возвращается как AnonymousAuthenticationTokenкак таковой: ![enter image description here](https://i.stack.imgur.com/DH6Qj.png)
Я добавил эти зависимости:
<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
является нулевым, и, как я уже говорил, аутентификация, проводимая в контексте безопасности, называется AnonymousAuthentication. Где проблема не обеспечения правильных объектов аутентификации?