Skip to content
Marlon Carvalho edited this page Jul 19, 2015 · 2 revisions

Interceptors are useful to implement features like authentication, cors, and body transformations. For example, create an interceptor if you want to intercept a request before your API method has been called and check if the user has authorization to access this resource.

You define an interceptor using the @Interceptor annotation and defining when it must be called (Interceptor.BEFORE or Interceptor.AFTER) and its priority in the chain. Observe that your annotated class must have a method named intercept receiving only one argument of the type Chain as in the example below.

@Interceptor(when: Interceptor.AFTER, priority: 0)
class Cors {
    void intercept(Chain chain) {
        chain.response.headers["Access-Control-Allow-Origin"] = "*";
        chain.response.headers["Access-Control-Allow-Credentials"] = "true";
        chain.response.headers["Access-Control-Allow-Methods"] = "GET, POST, DELETE, PUT";
        chain.response.headers["Access-Control-Allow-Headers"] = "*";
    }        
}

You can do a lot of things in your interceptor including manipulate the request headers, as pointed in the example above. You're even able to abort the execution before your resource method has been called.

@Interceptor(when:Interceptor.BEFORE, priority: 1)
class Authentication {
        
    void intercept(Chain chain) {
        String token = chain.request.headers["X-Token"];
        if (token != "Test") {
          chain.abort(new Response()
            ..body = "{\"error\":\"Permission Denied\"}"
            ..statusCode = 401);
        }
    }
}
Clone this wiki locally