Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

CORS in Grails 3 Using an Interceptor

DZone's Guide to

CORS in Grails 3 Using an Interceptor

· Java Zone
Free Resource

Make it happen: rapid app development on Kubernetes as a managed service.

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.



Tutorial: WordPress as distributed microservices on Kubernetes.

Topics:

Published at DZone with permission of Brian Swartzfager, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}