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
Where did I make mistake?
Update:
I have following set in my google oauth client config:
However, it still gives same error.
CodePudding user response:
The error shows that accounts.google.com doesn't accept request from localhost.... try to configure your google api (oauth) to accept requests from your domain (i'm not sure it would accept "localhost" as a valid domain because of obvious security reasons)
CodePudding user response:
The google login was successful, but still it was giving error that Access to XMLHttpRequest at https://acounts/google.com/o/ouath2/v2/auth
was blocked. There was not reason to hit this URL after successful login. As error says, this URL was hit by redirection to localhost:8080/api/user
. So somehow request to this URL did not have necessary information indicating earlier successful google login.
I checked the network traffic. The response from spring server after successful google login had JSESSIONID
cookie. But afterwards, the request to localhost:8080/api/user
did not have this cookie. So server was considering this as a new user request and trying to redirect it to google.
The request to localhost:8080/api/user
was HMLHttpRequest
using axios. So to include existing cookies to axios get request, I added following line before actually making the request:
axios.defaults.withCredentials = true
and now request to localhost:8080/api/user
had JSESSIONID
and hence it started working without any error.