Configuring CORS with Spring Boot
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 | // no credentials |
Add a @CrossOrigin
annotation to the controller method
1 |
|
1 | // with credentials |
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
responding a successful result to the preflight request. For example
1
2
3
4
5HTTP/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: 86400adding the following headers to the HTTP response headers
1
2
3
4Access-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 |
|
1 | // with credentials |
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 |
|
1 | // with credentials |
- pathPattern:
/myRequestMapping
,/**
,/myRequestMapping/**
,/*
- allowedOrigins: By default, all origins are allowed. Its default value is
*
. You can specify allowed origins like"http://localhost"
. - allowedMethods: By default,
GET
,HEAD
, andPOST
methods are allowed. You can enable all methods by setting its value to"GET", "POST", "HEAD", "PUT", "DELETE"
.
Filters
1 |
|
1 | // with credentials |