skip to Main Content

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


  1. To help clarify things, here’s a breakdown of how to send requests between React and Spring Boot in an OAuth2 setup and why withCredentials is important:

    1. Why withCredentials? When using OAuth2, authentication tokens
      (like cookies or JWTs) are stored on the client. The
      withCredentials: true setting in axios is needed to ensure that
      these 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.
    2. The 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 or
      CORS error, as it can’t recognize the client as authenticated.
    3. Simple Example of a POST Request Here’s a basic example of how to
      set up a POST request to your Spring Boot API with axios, ensuring
      credentials are included:
      axios.post('http://localhost:8081/api/resource', {
            data: { key: "value" }
        }, { withCredentials: true })
        .then(response => {
            console.log('Success:', response.data);
        })
        .catch(error => {
            console.error('Error:', error);
        });
    
    Login or Signup to reply.
  2. To answer you question in the comment related to CORS issue, this is Example of Handling CORS in Spring Boot Make sure your Spring Boot backend is configured to handle CORS for specific origins and methods. In your WebConfig, set up CORS like this:

    @Configuration
    public class WebConfig implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost:3000")
                    .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                    .allowCredentials(true);
        }
    }
    

    Spring Security Configuration for OAuth2 Your security config should allow authenticated requests to your protected endpoints, and ensure that requests from localhost:3000 can reach the backend. For example:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .cors()
                .and()
                .authorizeRequests()
                .antMatchers("/user-info", "/api/resource").authenticated()
                .anyRequest().permitAll()
                .and()
                .oauth2Login();
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search