DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • Knowing and Valuing Apache Kafka’s ISR (In-Sync Replicas)
  • SRE vs. DevOps
  • Cucumber Selenium Tutorial: A Comprehensive Guide With Examples and Best Practices
  • 5 Key Concepts for MQTT Broker in Sparkplug Specification

Trending

  • Knowing and Valuing Apache Kafka’s ISR (In-Sync Replicas)
  • SRE vs. DevOps
  • Cucumber Selenium Tutorial: A Comprehensive Guide With Examples and Best Practices
  • 5 Key Concepts for MQTT Broker in Sparkplug Specification

CORS in Grails 3 Using an Interceptor

Brian Swartzfager user avatar by
Brian Swartzfager
·
May. 13, 15 · Interview
Like (1)
Save
Tweet
Share
8.01K Views

Join the DZone community and get the full member experience.

Join For Free

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.



Grail (web browser)

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

Opinions expressed by DZone contributors are their own.

Trending

  • Knowing and Valuing Apache Kafka’s ISR (In-Sync Replicas)
  • SRE vs. DevOps
  • Cucumber Selenium Tutorial: A Comprehensive Guide With Examples and Best Practices
  • 5 Key Concepts for MQTT Broker in Sparkplug Specification

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: