I am currently a novice web developer and I am trying to setup some basic interactions with my frontend and backend using React and Springboot.
I am confused as how am I supposed to send requests once I have authenticated myself through OAuth2 Google login. I am using axios and I have managed to fetch a request to my backend for user info after login:
useEffect(()=>{
axios.get('http://localhost:8081/user-info',{withCredentials: true})
.then(response => {
setUser(response.data);
})
.catch(error =>{
console.error('Error occured: ',error);
});
})
@RestController
public class UserController {
@GetMapping("/user-info")
public Map<String, Object> getUserInfo(@AuthenticationPrincipal OAuth2User principal) {
return principal.getAttributes();
}
The response data is being successfully saved. Though, what is the purpose of using the withCredentials attribute. Does it have any effect on the request and is it necessary. I have already set up a WebConfig file that accepts CORS. I don’t understand why do I get a CORS error when I remove @AuthenticationPrincipal OAuth2User principal
, though it works fine with it. I don’t know how to set up a proper post request as I constantly get a CORS error. I would appreciate if a simple example of a POST request could be demonstrated.
2
Answers
To help clarify things, here’s a breakdown of how to send requests between React and Spring Boot in an
OAuth2
setup and whywithCredentials
is important:withCredentials
? When usingOAuth2
, authentication tokens(like cookies or JWTs) are stored on the client. The
withCredentials: true
setting in axios is needed to ensure thatthese tokens are sent with each request to authenticate the user on
the backend. Without it, your requests will be treated as
unauthenticated, which is likely why you’re getting
CORS errors
without it.
CORS Error
Issue:CORS errors
happen because your frontend(React, typically running on localhost:3000) is sending requests to
a different origin (Spring Boot at localhost:8081).
OAuth2
security configuration often requires a valid user context, and
without a valid token or session, Spring Boot will return a
401
orCORS error
, as it can’t recognize the client asauthenticated
.POST Request
Here’s a basic example of how toset up a
POST request
to your Spring Boot API with axios, ensuringcredentials are included:
To answer you question in the comment related to
CORS
issue, this is Example of HandlingCORS
in Spring Boot Make sure your Spring Boot backend is configured to handleCORS
for specific origins and methods. In yourWebConfig
, set upCORS
like this:Spring Security Configuration for
OAuth2
Your security config should allow authenticated requests to your protected endpoints, and ensure that requests fromlocalhost:3000
can reach the backend. For example: