Home > Software engineering >  @CrossOrigin(origins = { "*" }) not working for Springboot React app
@CrossOrigin(origins = { "*" }) not working for Springboot React app

Time:09-29

I have a Springboot backend and a React frontend and up until today, they were working fine. I was able to send and receive requests/responses. The other StackOverflow questions/answers all simply add @CrossOrigin(origins = { "*" }) but that is not working for me.

Now, all of a sudden, I am getting the error:

Access to XMLHttpRequest at 'http://localhost:8080/api/employees' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

However, I DO have CORS setup as far as I can tell. Like I said, it was working and now it isn't even though I did not change the CORS origins.

This is what I have in my Springboot backend:

@CrossOrigin(origins = { "*" })
@RestController
@RequestMapping("/api/")
public class EmployeeController {

    // Auto-inject EmployeeServices Class into this class so we can use the object
    // without calling 'new EmployeeServices'
    @Autowired
    private EmployeeServices employeeServices;

    // GET all employees
    @GetMapping("/employees")
    public List<Employee> getAllEmployees() {
        return employeeServices.getAllEmployees();
    }
}

The only thing I have done since it last worked was add the requirement to have JsonWebToken as a header for all requests. This works in Postman: Postman Results

I tried adding a hardcoded JWT to my axios request, just incase the JWT is what is giving me the CORS error:

class EmployeeService {
  getEmployees() {
    console.log("getting employees!");
    console.log("Environment variable: "   process.env.NODE_ENV);

    let config = {
      headers: {
        Authorization:
          "Bearer "  
          "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJmb28iLCJleHAiOjE2MzI3ODgwNzgsImlhdCI6MTYzMjc1MjA3OH0.ynUaU9IR893O7uaEjaQ6xPSQh9dEIWdU0DYwwRfXHHM",
      },
    };
    return axios
      .get(API_BASE_URL   "employees", null, config)
      .then(console.log("did it!"));
  }
}

But when I go to the webpage and let React make the request, I get the CORS error. What is going on? Shouldn't the * enable all origins? Is there anything I need listed in my frontend to make this work?

ERRORS

Thanks!

CodePudding user response:

This is what I use:

@Bean
public CorsConfigurationSource corsConfiguration() {
    CorsConfiguration corsConfig = new CorsConfiguration();
    corsConfig.applyPermitDefaultValues();
    corsConfig.addAllowedOrigin("http://localhost:3000");
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", corsConfig);
    return source;
}

Perhaps you only need to change to "/**" but at least this should get you started.

EDIT: Complete example might help Spring Webflux JWT Security Demo

  • Related