CORS in Grails 3 Using An Interceptor

Grails , Grails 3.x Add comments

(UPDATE: While the technique described here enables CORS for GET requests and non-preflighted POST requests, it does not work for the typical POST requests involving JSON used in Angular.  A better solution is the servlet filter posted by the author of the CORS plugin for Grails 2.x, David Tinker, found here: https://github.com/davidtinker/grails-cors/blob/master/README.md).

The other day I started working on a personal project involving Angular 1.x and the latest version of Grails (3.0.1).  I created a Grails controller with a method that returned a list of domain class objects as JSON, while on the Angular side I wrote a service method to make an HTTP request to retrieve that JSON.  But because the HTTP request came from a different domain, it was disallowed:  I needed to instruct Grails to accept the request via CORS (cross-origin resource sharing).

After some trial-and-error, I came up with a solution involving the Interceptor artefact introducted in Grails 3 (note to non-Grails users: "artefact" is the correct spelling of the Grails term for certain objects).  I created a RestInterceptor that would add the necessary CORS headers to the response:


package demo

class RestInterceptor {

    RestInterceptor() {
        //The widgets controller contains the method that returns the needed JSON
        match( controller: "widgets" )
    }

    boolean before() {
        //My Angular app's domain is local.test, so it needs to be the allowed origin
        header( "Access-Control-Allow-Origin", "http://local.test" )
        header( "Access-Control-Allow-Credentials", "true" )
        header( "Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE" )
        header( "Access-Control-Max-Age", "3600" )
        true
    }

    boolean after() { true }

}

A few notes from the experiments that lead to the above example:

  • As noted in the Interceptors documentation, interceptors are matched with controllers of the same name.  What isn't explictly metioned if that you create an Interceptor that does NOT match up with a controller (there is no "RestController" in my Grails app), you need to define a matcher like in the example above or Grails will throw an error.

  • So in regards to the previous point, if I only needed to allow CORS for the methods in my WidgetsController, I could have simply created an interceptor named WidgetsInterceptor and left off the matcher.  But it's far more likely that I'll have multiple controllers answering REST requests, so it makes sense to have one interceptor that can enable CORS for all of the relevant requests based on the matcher logic.

  • I did run into unexpected behavior when trying to define a reasonble matcher (per the supported matcher arguments), one that would work with mutliple controllers without having to list each and every controller:

    • uri:  I thought perhaps I could create a URI prefix like "/rest" or "/api" that I could use in UrlMapping statements to declare which mappings would allow CORS.  But what I found was that using the "uri" argument essentially matched every request, even when the URI in question didn't exist.  It was akin to using matchAll().  Either I'm missing something (in which case the documentation needs to give more guidance) or there's a bug in that behavior.

    • method:  Attempted to have the interceptor add the CORS headers to every incoming "GET" request.  Didn't work, but at least it failed as opposed to matching all incoming requests like the aforementioned "uri" argument.

    • namespace:  The namespace argument does work, but only if you have the namespace specified in the relevant UrlMapping statement as well as in the controller. An example URL mapping:

      
      //The Angular request is made to "http://localhost:8080/rest/listWidgets"
      '/rest/listWidgets' {
          controller = 'widgets'
          //Same namespace set as a static property in the WidgetsController
          namespace = 'restSpace'
          //The controller method that returns the JSON
          action = 'listWidgets'
       }
      
  • Grails 3 still supports the older beforeInterceptor() and afterInterceptor() controller methods.  I tried adding the CORS headers to the response using a beforeInterceptor() method in my WidgetsController but had no luck.  It's quite possible I just wasn't doing it right, but I did find a Grails GitHub issue that claimed beforeInterceptor() wasn't working properly.  In either case, the standalone interceptor seems like a better option.

  • For folks still using Grails 2.x, there is a CORS plugin available that lets you manage CORS behavior via settings in Config.groovy.  Wouldn't be surprised to see someone develop a similar plugin for Grails 3 eventually.

2 responses to “CORS in Grails 3 Using An Interceptor”

  1. Phill Says:
    I can't get it working with POST, DELETE and PUT even though i have:
    header( "Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE" )

    Any idea why?
  2. Brian Says:
    @Phill: In my focus on simply getting JSON data returned from Grails so I could try out an idea I had about returning object metadata, I neglected to verify that this would work for POST requests.

    I played with it for awhile today and got as far as determining that it was an issue with preflight requests: since the standard Angular $http POST action transmits the data as JSON it necessitates the preflight process (if you were to set the POST content type to "text/plain" it would work). But adding the additional headers involved with preflight requests to the interceptor didn't seem to help.

    Fortunately, the guy who wrote the CORS plugin for Grails 2.x recently updated his repo with instructions on how to handle CORS in Grails 3.x. I just tried it out and it worked for me, so go check that out - https://github.com/davidtinker/grails-cors/blob/master/README.md.

Leave a Reply