Search code examples
grailsspring-securitygrails-plugin

Securing Controller Actions by User in Grails


I am using the Grails security plugin on a project. I am using the annotations on controller actions to restrict access to certain classes of users such as 'ROLE_ADMIN' or 'ROLE_USER'.

(using this as the basis for what I am doing: http://grails-plugins.github.com/grails-spring-security-core/docs/manual/guide/5%20Configuring%20Request%20Mappings%20to%20Secure%20URLs.html#5.1%20Defining%20Secured%20Annotations)

My question is, how do I restrict an action so a user can only see information about themselves. For instance, lets say I have a user with id = 1. If I have an action that shows information about the user at:

mySite/User/Show/1

how do I prevent that same user with id=1 from being able to access

mySite/User/Show/2

? Is there a simple way to do this?


Solution

  • You can also use Grails controller interceptor if you want to apply same logic to multiple actions

    class SomeController {
    
     def beforeInterceptor = [action: this.&checkUser ] 
    
       def springSecurityService
    
    def checkUser() {
        User user = User.get(params)
           User logged = User.get(springSecurityService.principal.id)
           if (user.id != logged.id) {
       {
           redirect(action: "accessDenied", controller='access' id: params.long("id")) //re-direct accessDenied page
       return false
       }
        return true;
    }
    

    }

       Class AccessController{
         def accessDenied= {
    
            render(view: "accessDenied")
    
        }
     }