Contents
  1. 1. Configuring HTTP Request CORS
    1. 1.1. Controller CORS Configuration
      1. 1.1.1. Use @CrossOrigin annotation
      2. 1.1.2. Update HTTP response headers
    2. 1.2. Global CORS configuration
      1. 1.2.1. WebMvcConfigurer.addCorsMappings
      2. 1.2.2. Filters

In this post, we’ll cover how to configure CORS in a Spring Boot project. If you want to understand how CORS works, you can check out the article Understanding CORS.

Configuring HTTP Request CORS

Controller CORS Configuration

Use @CrossOrigin annotation

Add a @CrossOrigin annotation to the controller class

1
2
3
4
5
6
7
8
9
10
// no credentials
@CrossOrigin
@RestController
@RequestMapping("/my")
public class MyController {
@GetMapping
public String testGet() {
return "hello \n" + new Date();
}
}

Add a @CrossOrigin annotation to the controller method

1
2
3
4
5
6
7
8
9
10
@RestController
@RequestMapping("/my")
public class MyController {
// no credentials
@CrossOrigin
@GetMapping
public String testGet() {
return "hello \n" + new Date();
}
}
1
2
3
4
// with credentials
@CrossOrigin(origins = {"http://localhost"}, allowCredentials = "true")
// or
@CrossOrigin(originPatterns = {"http://localhost:[*]"}, allowCredentials = "true")

Properties of CrossOrigin

  • origins: by default, it’s *. You can specify allowed origins like @CrossOrigin(origins = {"http://localhost"}). You also can specify allowed origins by patterns like @CrossOrigin(originPatterns = {"http://*.taogen.com:[*]"}).

Add a @CrossOrigin annotation to the controller method or the controller class. It is equivalent to

  1. responding a successful result to the preflight request. For example

    1
    2
    3
    4
    5
    HTTP/1.1 204 No Content
    Connection: keep-alive
    Access-Control-Allow-Origin: https://foo.bar.org
    Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
    Access-Control-Max-Age: 86400
  2. adding the following headers to the HTTP response headers

    1
    2
    3
    4
    Access-Control-Allow-Origin: *
    Vary: Access-Control-Request-Headers
    Vary: Access-Control-Request-Method
    Vary: Origin

Update HTTP response headers

Only for GET, POST and HEAD requests without custom headers. In other words, it does not work for preflight requests.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@RestController
@RequestMapping("/my")
public class MyController {

@GetMapping
public String testGet(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Max-Age", "86400");
return "test get\n" + new Date();
}

@PostMapping
public String testPost(HttpServletResponse response) {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Max-Age", "86400");
return "test post\n" + new Date();
}
}
1
2
3
4
// with credentials
response.setHeader("Access-Control-Allow-Origin", "{your_host}"); // e.g. http://localhost or reqs.getHeader("Origin")
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Max-Age", "86400");

For ‘DELETE + Preflight’ or ‘PUT + Preflight’ requests, adding header ‘Access-Control-Allow-Origin: *’ to HttpServletResponse does not enable CORS. This will result in the following error

1
Access to XMLHttpRequest at 'http://localhost:8080/my' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

For requests with custom headers, adding header ‘Access-Control-Allow-Origin: *’ to HttpServletResponse does not enable CORS. This will result in the following error

1
Access to XMLHttpRequest at 'http://localhost:8080/my' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Global CORS configuration

WebMvcConfigurer.addCorsMappings

The WebMvcConfigurer.addCorsMappings has the same function as the @CrossOrigin annotation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Configuration
public class CorsConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
// no credentials
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("GET", "POST", "HEAD", "PUT", "DELETE", "PATCH");
}
};
}
}
1
2
3
4
5
// with credentials
registry.addMapping("/**")
.allowedOrigins("{your_host}") // e.g. http://localhost
.allowCredentials(true)
.allowedMethods("GET", "POST", "HEAD", "PUT", "DELETE", "PATCH");
  • pathPattern: /myRequestMapping, /**, /myRequestMapping/**, /*
  • allowedOrigins: By default, all origins are allowed. Its default value is *. You can specify allowed origins like "http://localhost".
  • allowedOriginPatterns: for example, http://localhost:[*], http://192.168.0.*:[*], https://demo.com
  • allowedMethods: By default, GET, HEAD, and POST methods are allowed. You can enable all methods by setting its value to "GET", "POST", "HEAD", "PUT", "DELETE", "PATCH".

Filters

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Component
public class CorsFilter implements Filter {

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest reqs = (HttpServletRequest) req;
// no credentials
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT, PATCH");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Max-Age", "86400");
chain.doFilter(req, res);
}
}
1
2
3
4
5
6
// with credentials
response.setHeader("Access-Control-Allow-Origin", "{your_host}"); // e.g. http://localhost or reqs.getHeader("Origin")
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT, PATCH");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.setHeader("Access-Control-Max-Age", "86400");
Contents
  1. 1. Configuring HTTP Request CORS
    1. 1.1. Controller CORS Configuration
      1. 1.1.1. Use @CrossOrigin annotation
      2. 1.1.2. Update HTTP response headers
    2. 1.2. Global CORS configuration
      1. 1.2.1. WebMvcConfigurer.addCorsMappings
      2. 1.2.2. Filters