How to enable cross origin request policy in spring boot?

Overview

Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers. It blocks web pages from making requests to a different domain than the one that served the web page. This is done to prevent malicious websites from stealing sensitive information such as user login credentials. CORS allows web pages to make cross-origin requests if the server hosting the requested resource explicitly allows it.

When a browser receives a response from a server, it checks the value of the "Access-Control-Allow-Origin" header. If the value of this header is "" or if it matches the origin of the web page making the request, the browser will allow the request. If the value of this header is not " or does not match the origin of the web page making the request, the browser will block the request.

"No 'Access-Control-Allow-Origin' header is present on the requested resource" error occurs when a web page is trying to make a cross-origin request and the server that is hosting the requested resource has not enabled CORS or has not configured it to allow requests from the origin of the web page making the request.

To resolve this error, you need to enable CORS on the server that is hosting the requested resource.

Here are a few ways to do this in Spring Boot:

Using the @CrossOrigin annotation: You can use the @CrossOrigin annotation on your controller class or methods to enable CORS for specific endpoints.

@CrossOrigin
@RestController
public class MyController {
    // ...
}?

 Or Create a new global configuration class and annotate it with @Configuration and @EnableWebMvc. In this class, you will add the CORS filter to your application.

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "HEAD")
                .allowedOrigins("*")
                .allowCredentials(true);
    }
}?

In the addCorsMappings method, you can configure various options for the CORS filter. In the example above, all methods, origins, and credentials are allowed.

If you want to allow certain origins only, you can replace .allowedOrigins("*") with a list of specific origins.

.allowedOrigins("https://geekscoder.com", "https://blog.geekscoder.com")

Now, you can build and run your application. The CORS filter will now be applied to all requests, allowing cross-origin requests to be handled correctly.

Keep in mind that, some browsers may still block cross-origin requests even if your server is configured to allow them, you can use CORS plugins for the browser for testing.