Configuring CORS with Spring Boot
In this post, I will 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
// no credentials |
Add a @CrossOrigin
annotation to the controller method
|
// 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
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: 86400adding the following headers to the HTTP response headers
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.
|
// 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
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
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.
|
// with credentials |
- 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
, andPOST
methods are allowed. You can enable all methods by setting its value to"GET", "POST", "HEAD", "PUT", "DELETE", "PATCH"
.
Filters
|
// with credentials |