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.
3 replies on “restrict a Grails controller to localhost access only”
[…] Dieser Eintrag wurde auf Twitter von groovyblogs.org erwähnt. groovyblogs.org sagte: restrict a Grails controller to localhost access only — http://bit.ly/caurTK — Armbruster IT Blog » grails […]
Interceptors are good but if you want to restrict access to more than one controller you can also use Filters 🙂
Good catch, thanks. I should have mentioned that.