Guide to CORS in Spring Boot

Aakash Sorathiya
Published in
2 min readMar 23, 2021


What is CORS?

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any other origins (domain, scheme, or port) than its own from which a browser should permit loading of resources.

For example, web app on domain makes the HttpRequest to a web app on domain

How CORS work?

In modern browsers due to security reasons cross-origin HTTP request is not allowed.

Whenever there is a CORS request browser will send a preflight request prior to sending the actual request to find out whether CORS request is valid or not.

The preflight request is an OPTIONS request made to the same HTTP path as the actual request, with a couple of HTTP headers:

  • Origin — The origin header that would be included with the actual request being made by the website.
  • Access-Control-Request-Method — The method of the actual request being made by the website.
  • Access-Control-Request-Headers — A comma-separated list of headers that would be included in the actual request.

If web server wish to support the CORS request, it must respond to the preflight request with the following headers:

  • Access-Control-Allow-Origin — The whitelisted origin, or ‘*’
  • Access-Control-Allow-Methods — A comma-separated list of HTTP methods the web server wishes to permit for cross-origin requests
  • Access-Control-Allow-Headers — A comma-separated list of HTTP headers the web server wishes to permit for cross-origin requests

If the preflight request fails browser will not send the original request to the server.

Configuring CORS in SpringBoot application

To enable web security in spring boot we will first add the maven dependency spring-starter-security in pom file


Now we will add configuration class to set config for CORS

public class SecurityConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;

According to the above configs the response of the preflight request will look like:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: *





Aakash Sorathiya

A software developer with a strong passion for self-improvement.