My spring boot app is running on localhost:8080
and react app on localhost:3000
.
I have configured the Outh2 in my spring boot app as follows:
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception
{
http.requestMatchers().antMatchers("/**")
.and()
.authorizeRequests().anyRequest().authenticated()
.and()
.oauth2Login()
.defaultSuccessUrl("http://localhost:3000/dashboard");
.userInfoEndpoint()
.oidcUserService(customOidcUserService); // checks if user exists in db, if not creates one
return http.build();
}
I have a login button on page at localhost:3000\login
which has its href='http://localhost:8080/oauth2/authorization/google'
. So when I click this button, it redirects to google, after authenticating to google, it redirects back to http://localhost:3000/dashboard
as stated in above config. On the load of /dashboard
page , I am trying to fetch the data by first calling REST endpoint localhost:8080/api/user
. The corresponding RestController
looks like this:
@RestController
@RequestMapping("/api")
public class SecController {
@GetMapping("/user")
public Map<String, Object> user(@AuthenticationPrincipal OAuth2User principal) {
return Collections.singletonMap("email", ((OidcUserPrincipal)principal).getUsername());
}
}
But it gave me following error:
When I manually try to browse localhost:8080/api/user
, it correctly returns currently logged in user information:
So, user is indeed getting correctly logged in. After googling for error, I added following bean as suggested here:
@Bean
public CorsConfigurationSource corsConfigurationSource() {
final CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(ImmutableList.of("http://localhost:3000"));
configuration.setAllowedMethods(ImmutableList.of("HEAD","GET", "POST", "PUT", "DELETE", "PATCH"));
configuration.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type"));
final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
and also added .and().cors()
in filterChain()
method, but now it gives me following error:
Where did I make mistake?
Update:
I have following set in my google oauth client config:
However, it still gives same error.