Thilina Rathnayake
Thilina Rathnayake

Reputation: 90

browser says " request has been blocked by CORS policy" when calling to a spring boot get method from react js using axios

maybe this question is duplicated, but I didn't manage to solve the issue by reading any posts.

when do a get request by adding a token to the header using postman, it returns the correct response. but it doesn't work with react js. here is my axios get request

axios
  .get("http://localhost:8080/vehicle/vehicle", {
    headers: {
      authorization: AuthStr,
    },
  })
  .then((response) => response.data)
  .then(
    (data) => {
      console.log(data);
      this.setState({ Vehicles: data });
    },
    (error) => {
      alert(error);
      //localStorage.clear();
    }
  );

I also have added the @CrossOrigin to the controller as shown bellow.

 @RestController
 @RequestMapping("/vehicle")
 @CrossOrigin(origins = "http://localhost:3000")
 public class VehicleController {}

and here is my configure method

  @Override
  protected void configure(HttpSecurity httpSecurity) throws Exception {
     // We don't need CSRF for this example
     httpSecurity.csrf().disable()
             // dont authenticate this particular request
             
 .authorizeRequests().antMatchers("/authenticate","/user/registerUser","/user/regUser").permitAll().
             // all other requests need to be authenticated
             anyRequest().authenticated().and().
             // make sure we use stateless session; session won't be used to
             // store user's state.
             
  exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

             // Add a filter to validate the tokens with every request
  httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

}

Upvotes: 2

Views: 449

Answers (1)

Chanura Janith
Chanura Janith

Reputation: 36

Change your configure method like this

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {

httpSecurity.csrf().disable().authorizeRequests().antMatchers("/authenticate","/user/registerUser","/user/regUser").permitAll().requestMatchers(CorsUtils::isPreFlightRequest).permitAll().
         // all other requests need to be authenticated
         anyRequest().authenticated().and().
         // make sure we use stateless session; session won't be used to
         // store user's state.
       exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

         // Add a filter to validate the tokens with every request
     httpSecurity.addFilterBefore(jwtRequestFilter, 
     UsernamePasswordAuthenticationFilter.class);

   }

Upvotes: 2

Related Questions