8.4 CORS
Spring Boot provides CORS support out of the box, but it is difficult to configure in a Grails application due to the way UrlMappings are used instead of annotations that define URLs. Starting with Grails 3.2.1, we have added a way to configure CORS that makes sense in a Grails application.
Once enabled, the default setting is "wide open".
application.yml
grails:cors:enabled: true
That will produce a mapping to all urls /** with:
| allowedOrigins | [''] |
| allowedMethods | [''] |
| allowedHeaders | ['*'] |
| exposedHeaders | null |
| maxAge | 1800 |
| allowCredentials | true |
Some of these settings come directly from Spring Boot and can change in future versions. See Spring CORS Configuration Documentation
All of those settings can be easily overridden.
application.yml
grails:cors:enabled: trueallowedOrigins:- http://localhost:5000
In the example above, the allowedOrigins setting will replace [*].
You can also configure different URLs.
application.yml
grails:cors:enabled: trueallowedHeaders:- Content-Typemappings:/api/**:allowedOrigins:- http://localhost:5000# Other configurations not specified default to the global config
Specifying at least one mapping will disable the creation of the global mapping (/**). If you wish to keep that setting, you should specify it along with your other mappings. |
The settings above will produce a single mapping of /api/** with the following settings:
| allowedOrigins | ['http://localhost:5000'] |
| allowedMethods | ['*'] |
| allowedHeaders | ['Content-Type'] |
| exposedHeaders | null |
| maxAge | 1800 |
| allowCredentials | true |
If you don’t wish to override any of the default settings, but only want to specify URLs, you can do so like this example:
application.yml
grails:cors:enabled: truemappings:/api/**: inherit