【发布时间】:2020-02-16 16:35:50
【问题描述】:
我正在尝试使用自定义 defaultSuccessUrl 将使用 google 登录到我的 Spring Boot 应用程序中。身份验证似乎通过了,但是当我到达成功 url 端点时,我无法获得 OAuth2AuthenticationToken (如果将其作为方法的参数,则它为空)并且当我从安全上下文中获取身份验证时,它返回为 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>
这是我的安全配置:
@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 为空,正如我之前所说的安全上下文中的身份验证是匿名身份验证。没有提供正确的 Authentication 对象的问题在哪里?
【问题讨论】:
标签: java spring spring-boot oauth-2.0 google-oauth