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

  1. grails:
  2. cors:
  3. enabled: true

That will produce a mapping to all urls /** with:

allowedOrigins['']
allowedMethods['']
allowedHeaders['*']
exposedHeadersnull
maxAge1800
allowCredentialstrue

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

  1. grails:
  2. cors:
  3. enabled: true
  4. allowedOrigins:
  5. - http://localhost:5000

In the example above, the allowedOrigins setting will replace [*].

You can also configure different URLs.

application.yml

  1. grails:
  2. cors:
  3. enabled: true
  4. allowedHeaders:
  5. - Content-Type
  6. mappings:
  7. /api/**:
  8. allowedOrigins:
  9. - http://localhost:5000
  10. # 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']
exposedHeadersnull
maxAge1800
allowCredentialstrue

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

  1. grails:
  2. cors:
  3. enabled: true
  4. mappings:
  5. /api/**: inherit