Search code examples
grailscors

Grails 3 configuring CORS for multiple mappings in application.yml


I've tried following the official documentation guide here http://docs.grails.org/3.3.11/guide/single.html#cors but strangely I found that only the first mapping will ever get applied.

Their example:

grails:
    cors:
        enabled: true
        mappings:
            /api/**: inherit

What I assumed would work but doesn't (only the first mapping gets applied):

    grails:
        cors:
            enabled: true
            mappings:
                /api/**: inherit
                /api2/**: inherit
                ..

I must be missing something really simple as I was surprised to find no documentation or questions for multiple mappings like this. Any ideas on this?


Solution

  • Yeah that kind of killed me too. We solved this in the BeAPI Grails Plugin (which I maintain) by adding the mappings to the beapi_api.yml config file:

    corsInterceptor:
        includeEnvironments: ['development','test','production']
        excludeEnvironments: []
        networkGroups:
            open: ['http://localhost','http://localhost:8080','http://127.0.0.1','http://test.nosegrind.net','http://test.nosegrind.net:8080']
            public: ['http://localhost','http://localhost:8080','http://127.0.0.1','http://test.nosegrind.net','http://test.nosegrind.net:8080']
            private: ['http://localhost','http://localhost:8080','http://127.0.0.1','http://test.nosegrind.net','http://test.nosegrind.net:8080']
    

    Every request is checked to see what 'networkGroup' it belongs to (which is declared in the same config file):

    networkGroups: ['open','public','private']
    networkRoles:
        open: ['ROLE_ADMIN','ROLE_ANONYMOUS','ROLE_USER']
        public: ['ROLE_ADMIN','ROLE_USER']
        private: ['ROLE_ADMIN']
    

    This allows GROUP/ROLE checking along with FQDN/IP checking on the frontend when doing a CORS check.

    So all you have to do is add your FQDN/IP to the appropriate 'corsInterceptor.networkGroup'