Archive

Posts Tagged ‘tip’

restrict a Grails controller to localhost access only

April 19th, 2010 2 comments

A common requirement for many web applications is that some parts (aka controllers) should only be accessible from specifc ip addresses. Typically controllers doing some administrative or maintenance work must be protected from non-authroized access. The most complete solution for this is using a full blown security framework like the Grails Acegi plugin. But there’s also a lean and quick solution for this in Grails: use a controller interceptor:

def beforeInterceptor = {
   if (!["127.0.0.1", "0:0:0:0:0:0:0:1"].contains(request.remoteAddr)) {
      render(status: 401, text: 'Access limited to localhost')
      return false
   }
}

Grails calls the beforeIntereceptor closure prior every action in a controller. Only if it returns true, the action is executed. In the code above if the client has a non-local IP address, a 401 error is returned with an error message. Note that localhost in IPv6 is 0:0:0:0:0:0:0:1, so it work both in IPv4 and IPv6 networks.

Categories: Uncategorized Tags: ,