我尝试使用自定义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。
1条答案
按热度按时间nmpmafwu1#
我有同样的问题,我的解决方案不是100%完美,但它的工作原理。你可以删除
使用
SessionCreationPolicy.STATELESS
成功登录后,您将仅以匿名身份转发到您的defaultSuccessUrl
(ROLE_ANONYMOUS)但如果删除
STATELESS
,则对象将被设置为OAuth2AuthenticationToken authentication
,并且在日志中,您将看到ROLE_USER的不同输出