In the previous article, we gave a detailed idea about what is CORS and how does it work. In this article we will explain the necessary configurations , one has to make in server side spring application to enable cross origin requests. Lets begin.
Enabling CORS
To enable Cross Origin Requests to enable the rest API, we have two ways to accomplish this.
Controller Level Configuration :
In this setup, we add annotation @CrossOrigin on top of controller class itself. With this configuration we are allowing cross origin resource sharing for all API’s within that controller. An example will make it more clear
@CrossOrigin @RestController public class UserController { public User getUser(@RequestParam("name") String name) { System.out.println("Hello "+name); return new User(1, name, "Male"); } }
By Default @CrossOrigin allows all origin, methods and header to access the rest API. To filter the requests, we can add attributes with the annotation and can customize the behavior as per our need. The attributes which we can add to the annotation are:
origins – @CrossOrigin(origin=”http://hello-world.example”)
maxAge – @CrossOrigin(maxAge = 600)
methods – @CrossOrigin(methods = “GET, PUT, DELETE, POST”)
allowedHeaders – @CrossOrigin(allowedHeaders = “Content-Type, Authorization”)
allowedCredentials – @CrossOrigin(allowedCredentials = true)
Method Level Configuration:
In this setup, we add @CrossOrigin annotation with the handler method. This will enable cross origin resource sharing for that particular method. Suppose we want a particular filter for CORS in a specific method inside a controller, then this method is useful. Lets look at an example
@RestController @CrossOrigin(origins = "", allowedHeaders = "*") public class UserController { @CrossOrigin(origins = "http://hellouser.com") @GetMapping(path="/user") public User getUser(@RequestParam("name") String name) { System.out.println("Hello "+name); return new User(1, name, "Male"); } }
Here with the method level configuration on getUser() , this method will only be accessible from domain http://hellouser.com. All other methods under UserController will be accessible from everywhere.
Global CORS configuration
This is the best way of configuration to enable CORS, if we want consistent configuration throughout the whole application. This behaves like a filter class which is executed at the beginning of application load. Lets see now an example of how we configure in spring boot.
@Configuration public class CorsConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("http://hellouser.com") .allowedMethods("GET, POST, DELETE, PUT"); } }; } }
Above configuration only allows domain “http://hellouser.com” to access the API’s of this web application. Multiple domains can be added separated by comma. If we don’t configure allowedMethods() above, all the HTTP method requests will be supported. To explicitly support a set of HTTP methods allowedMethods() should be used.
In case Spring security is added in the web application, CORS configuration can be enabled with spring security using below code
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
//other config
}
@Bean
CorsConfigurationSource corsConfigurationSource()
{
CorsConfiguration configuration = new CorsConfiguration();
configuration.setAllowedOrigins(Arrays.asList("https://helloworld.com"));
configuration.setAllowedMethods(Arrays.asList("GET","POST"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
}
Hope this article gives you a fair understanding of the different configurations you can make in your server side web application to enable cross origin requests.