|
| 1 | +[[cors]] |
| 2 | += CORS Support |
| 3 | + |
| 4 | +== Introduction |
| 5 | + |
| 6 | +For security reasons, browsers prohibit AJAX calls to resources residing outside the |
| 7 | +current origin. For example, as you're checking your bank account in one tab, you |
| 8 | +could have the evil.com website in another tab. The scripts from evil.com should not |
| 9 | +be able to make AJAX requests to your bank API (withdrawing money from your account!) |
| 10 | +using your credentials. |
| 11 | + |
| 12 | +http://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] |
| 13 | +(CORS) is a http://www.w3.org/TR/cors/[W3C specification] implemented by |
| 14 | +http://caniuse.com/#feat=cors[most browsers] that allows you to specify in a flexible |
| 15 | +way what kind of cross domain requests are authorized, instead of using some less secured |
| 16 | +and less powerful hacks like IFrame or JSONP. |
| 17 | + |
| 18 | +As of Spring Framework 4.2, CORS is supported out of the box. CORS requests |
| 19 | +(https://github.com/spring-projects/spring-framework/blob/master/spring-webmvc/src/main/java/org/springframework/web/servlet/FrameworkServlet.java#L906[including preflight ones with an `OPTIONS` method]) |
| 20 | +are automatically dispatched to the various `HandlerMapping` registered. They handle |
| 21 | +CORS preflight requests and intercept CORS simple and actual requests thanks to a |
| 22 | +http://docs.spring.io/spring/docs/4.2.x/javadoc-api/org/springframework/web/cors/CorsProcessor.html[CorsProcessor] |
| 23 | +implementation (https://github.com/spring-projects/spring-framework/blob/master/spring-web/src/main/java/org/springframework/web/cors/DefaultCorsProcessor.java[DefaultCorsProcessor] |
| 24 | +by default) in order to add the relevant CORS response headers (like `Access-Control-Allow-Origin`) |
| 25 | +based on the CORS configuration you have provided. |
| 26 | + |
| 27 | +[NOTE] |
| 28 | +==== |
| 29 | +Since CORS requests are automatically dispatched, you *do not need* to change |
| 30 | +`DispatcherServlet` `dispatchOptionsRequest` init parameter value, using its default value |
| 31 | +(`false`) is the recommended approach. |
| 32 | +==== |
| 33 | + |
| 34 | +== Controller method CORS configuration |
| 35 | + |
| 36 | +You can add to your `@RequestMapping` annotated handler method a |
| 37 | +http://docs.spring.io/spring/docs/4.2.x/javadoc-api/org/springframework/web/bind/annotation/CrossOrigin.html[`@CrossOrigin`] |
| 38 | +annotation in order to enable CORS on it (by default `@CrossOrigin` allows all origins |
| 39 | +and the HTTP methods specified in the `@RequestMapping` annotation): |
| 40 | + |
| 41 | +[source,java,indent=0] |
| 42 | +[subs="verbatim,quotes"] |
| 43 | +---- |
| 44 | +@RestController |
| 45 | +@RequestMapping("/account") |
| 46 | +public class AccountController { |
| 47 | +
|
| 48 | + @CrossOrigin |
| 49 | + @RequestMapping("/{id}") |
| 50 | + public Account retrieve(@PathVariable Long id) { |
| 51 | + // ... |
| 52 | + } |
| 53 | +
|
| 54 | + @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") |
| 55 | + public void remove(@PathVariable Long id) { |
| 56 | + // ... |
| 57 | + } |
| 58 | +} |
| 59 | +---- |
| 60 | + |
| 61 | +It is also possible to enable CORS for the whole controller: |
| 62 | + |
| 63 | +[source,java,indent=0] |
| 64 | +[subs="verbatim,quotes"] |
| 65 | +---- |
| 66 | +@CrossOrigin(origins = "http://domain2.com", maxAge = 3600) |
| 67 | +@RestController |
| 68 | +@RequestMapping("/account") |
| 69 | +public class AccountController { |
| 70 | +
|
| 71 | + @RequestMapping("/{id}") |
| 72 | + public Account retrieve(@PathVariable Long id) { |
| 73 | + // ... |
| 74 | + } |
| 75 | +
|
| 76 | + @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") |
| 77 | + public void remove(@PathVariable Long id) { |
| 78 | + // ... |
| 79 | + } |
| 80 | +} |
| 81 | +---- |
| 82 | + |
| 83 | +In this example CORS support is enabled for both `retrieve()` and `remove()` handler methods, and you can also see how you can customize the CORS configuration using `@CrossOrigin` attributes. |
| 84 | + |
| 85 | +You can even use both controller and method level CORS configurations, Spring will then combine both annotation attributes to create a merged CORS configuration. |
| 86 | + |
| 87 | +[source,java,indent=0] |
| 88 | +[subs="verbatim,quotes"] |
| 89 | +---- |
| 90 | +@CrossOrigin(maxAge = 3600) |
| 91 | +@RestController |
| 92 | +@RequestMapping("/account") |
| 93 | +public class AccountController { |
| 94 | +
|
| 95 | + @CrossOrigin(origins = "http://domain2.com") |
| 96 | + @RequestMapping("/{id}") |
| 97 | + public Account retrieve(@PathVariable Long id) { |
| 98 | + // ... |
| 99 | + } |
| 100 | +
|
| 101 | + @RequestMapping(method = RequestMethod.DELETE, value = "/{id}") |
| 102 | + public void remove(@PathVariable Long id) { |
| 103 | + // ... |
| 104 | + } |
| 105 | +} |
| 106 | +---- |
| 107 | + |
| 108 | +== Global CORS configuration |
| 109 | + |
| 110 | +In addition to fine-grained, annotation-based configuration you'll probably want to |
| 111 | +define some global CORS configuration as well. This is similar to using filters but can |
| 112 | +be declared withing Spring MVC and combined with fine-grained `@CrossOrigin` configuration. |
| 113 | +By default all origins and `GET`, `HEAD` and `POST` methods are allowed. |
| 114 | + |
| 115 | +=== JavaConfig |
| 116 | + |
| 117 | +Enabling CORS for the whole application is as simple as: |
| 118 | + |
| 119 | +[source,java,indent=0] |
| 120 | +[subs="verbatim,quotes"] |
| 121 | +---- |
| 122 | +@Configuration |
| 123 | +@EnableWebMvc |
| 124 | +public class WebConfig extends WebMvcConfigurerAdapter { |
| 125 | +
|
| 126 | + @Override |
| 127 | + public void addCorsMappings(CorsRegistry registry) { |
| 128 | + registry.addMapping("/**"); |
| 129 | + } |
| 130 | +} |
| 131 | +---- |
| 132 | + |
| 133 | +You can easily change any properties, as well as only apply this CORS configuration to a |
| 134 | +specific path pattern: |
| 135 | + |
| 136 | +[source,java,indent=0] |
| 137 | +[subs="verbatim,quotes"] |
| 138 | +---- |
| 139 | +@Configuration |
| 140 | +@EnableWebMvc |
| 141 | +public class WebConfig extends WebMvcConfigurerAdapter { |
| 142 | +
|
| 143 | + @Override |
| 144 | + public void addCorsMappings(CorsRegistry registry) { |
| 145 | + registry.addMapping("/api/**") |
| 146 | + .allowedOrigins("http://domain2.com") |
| 147 | + .allowedMethods("PUT", "DELETE") |
| 148 | + .allowedHeaders("header1", "header2", "header3") |
| 149 | + .exposedHeaders("header1", "header2") |
| 150 | + .allowCredentials(false).maxAge(3600); |
| 151 | + } |
| 152 | +} |
| 153 | +---- |
| 154 | + |
| 155 | +=== XML namespace |
| 156 | + |
| 157 | +This minimal XML configuration enable CORS on `/**` path pattern with the same default properties than the JavaConfig one: |
| 158 | + |
| 159 | +[source,xml,indent=0] |
| 160 | +[subs="verbatim"] |
| 161 | +---- |
| 162 | +<mvc:cors> |
| 163 | + <mvc:mapping path="/**" /> |
| 164 | +</mvc:cors> |
| 165 | +---- |
| 166 | + |
| 167 | +It is also possible to declare several CORS mappings with customized properties: |
| 168 | + |
| 169 | +[source,xml,indent=0] |
| 170 | +[subs="verbatim"] |
| 171 | +---- |
| 172 | +<mvc:cors> |
| 173 | +
|
| 174 | + <mvc:mapping path="/api/**" |
| 175 | + allowed-origins="http://domain1.com, http://domain2.com" |
| 176 | + allowed-methods="GET, PUT" |
| 177 | + allowed-headers="header1, header2, header3" |
| 178 | + exposed-headers="header1, header2" allow-credentials="false" |
| 179 | + max-age="123" /> |
| 180 | +
|
| 181 | + <mvc:mapping path="/resources/**" |
| 182 | + allowed-origins="http://domain1.com" /> |
| 183 | +
|
| 184 | +</mvc:cors> |
| 185 | +---- |
| 186 | + |
| 187 | +== Advanced Customizations |
| 188 | + |
| 189 | +http://docs.spring.io/spring/docs/4.2.x/javadoc-api/org/springframework/web/cors/CorsConfiguration.html[CorsConfiguration] |
| 190 | +allows you to specify how the CORS requests should be processed: allowed origins, headers, methods, etc. |
| 191 | +It can be provided in various ways: |
| 192 | + |
| 193 | + * http://docs.spring.io/spring/docs/4.2.x/javadoc-api/org/springframework/web/servlet/handler/AbstractHandlerMapping.html#setCorsConfiguration-java.util.Map-[`AbstractHandlerMapping#setCorsConfiguration()`] |
| 194 | + allows to specify a `Map` with several http://docs.spring.io/spring/docs/4.2.x/javadoc-api/org/springframework/web/cors/CorsConfiguration.html[CorsConfiguration] |
| 195 | + mapped on path patterns like `/api/**` |
| 196 | + * Subclasses can provide their own `CorsConfiguration` by overriding |
| 197 | + `AbstractHandlerMapping#getCorsConfiguration(Object, HttpServletRequest)` method |
| 198 | + * Handlers can implement http://docs.spring.io/spring/docs/4.2.x/javadoc-api/org/springframework/web/cors/CorsConfigurationSource.html[`CorsConfigurationSource`] |
| 199 | + interface (like https://github.com/spring-projects/spring-framework/blob/master/spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java[`ResourceHttpRequestHandler`] |
| 200 | + now does) in order to provide a http://docs.spring.io/spring/docs/4.2.x/javadoc-api/org/springframework/web/cors/CorsConfiguration.html[CorsConfiguration] |
| 201 | + for each request. |
0 commit comments