Spring OAuth2 名称始终为空。我正在尝试在 Spring Boot 中实现“使用 Google 登录”。我已经实现了 JWT 令牌功能。
我在使用谷歌登录时也面临同样的问题。有人有解决办法吗?我遵循同样的步骤
@GetMapping("/loginSuccess")
public String loginSuccess(@AuthenticationPrincipal OAuth2User oauthUser) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
System.out.println("Authentication principal: " + authentication.getPrincipal());
if (oauthUser == null) {
return "Error: OAuth2User is null. Authentication failed.";
}
String username = oauthUser.getAttribute("name");
JwtToken jwtToken = jwtUtils.generateTokenFromUsername(username);
return "Login successful! JWT Token: " + jwtToken;
}
这是我的安全配置
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors(cors -> cors.configurationSource(corsConfigurationSource()))
.csrf(csrf -> csrf.disable())
.authorizeHttpRequests(auth -> {
auth.requestMatchers(
antMatcher("/api/auth/**"),
antMatcher("/oauth2/**"),
antMatcher("/login/**")
).permitAll()
.anyRequest().authenticated();
})
.oauth2Login(oauth2 -> oauth2
.defaultSuccessUrl("/api/auth/loginSuccess")
.failureUrl("/api/auth/loginFailure")
)
.httpBasic()
.and()
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling()
.authenticationEntryPoint(unauthorizedHandler)
.and()
.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class)
.authenticationProvider(authenticationProvider());
return http.build();
错误:
Authentication principal: anonymousUser
2024-11-07T11:25:56.555+05:30 ERROR 12772 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.NullPointerException: Cannot invoke "org.springframework.security.oauth2.core.user.OAuth2User.getAttribute(String)" because "oauthUser" is null] with root cause
java.lang.NullPointerException: Cannot invoke "org.springframework.security.oauth2.core.user.OAuth2User.getAttribute(String)" because "oauthUser" is null
at com.wisedoctor.security.controllers.AuthController.loginSuccess(AuthController.java:279) ~[classes/:na]
不要使用这个
String username = oauthUser.getAttribute("name"); // This line cause NullPointer exception.
我们来使用吧
Authentication.getPrincipal()