17.4 Authentication

Grails has no default mechanism for authentication as it is possible to implement authentication in many different ways. It is however, easy to implement a simple authentication mechanism using interceptors. This is sufficient for simple use cases but it’s highly preferable to use an established security framework, for example by using the Spring Security or the Shiro plugin.

Interceptors let you apply authentication across all controllers or across a URI space. For example you can create a new set of filters in a class called grails-app/controllers/SecurityInterceptor.groovy by running:

  1. grails create-interceptor security

and implement your interception logic there:

  1. class SecurityInterceptor {
  2. SecurityInterceptor() {
  3. matchAll()
  4. .except(controller:'user', action:'login')
  5. }
  6. boolean before() {
  7. if (!session.user && actionName != "login") {
  8. redirect(controller: "user", action: "login")
  9. return false
  10. }
  11. return true
  12. }
  13. }

Here the interceptor intercepts execution before all actions except login are executed, and if there is no user in the session then redirect to the login action.

The login action itself is simple too:

  1. def login() {
  2. if (request.get) {
  3. return // render the login view
  4. }
  5. def u = User.findByLogin(params.login)
  6. if (u) {
  7. if (u.password == params.password) {
  8. session.user = u
  9. redirect(action: "home")
  10. }
  11. else {
  12. render(view: "login", model: [message: "Password incorrect"])
  13. }
  14. }
  15. else {
  16. render(view: "login", model: [message: "User not found"])
  17. }
  18. }