In Grails, interceptor use the concept of Aspect Oriented Programming (AOP) to intercept the programming logic before or after a controller method. Here we will create an ApiInterceptor
which will intercept all the method in a controller ApiController
before they are being called.
grails
to enter grails modecreate-interceptor Api
. This will create the file ApiInterceptor.groovy under the project/grails-app/controllers/PACKAGENAME/
We are going to intercept all methods in ApiController
. To do this, we need to tell ApiInterceptor
about it in its constructor.
ApiInterceptor() { match(controller: "api") }
Inside the interceptor class, there are three methods:
The before() method will be called before the controller's methods begin called. Likewise, the after() method will be called after a method from ApiController
is called. Both before() and after() return a boolean. If we return true, that means Grails should continue the normal routine. If we return false, it means we intercepted the routine, and we are suppose to handle what the HTTP response for the client.
Here, we are going to stop the user calling any of our api methods. This can be easily done by:
boolean before() { response.status = 401 render(text: "Unauthorized access") return false }
Of course, you can add some logic there to make this example more interesting. For example, we can add the checking in the request header to see if it contains some sort of token that match to our database. Like what we do in Grails's controller, we can access the variable request
, and response
inside an interceptor.