Search This Blog

Thursday, September 15, 2011

Roles and Permissions with Spring Security 3


With the objective of achieving a bigger granularity and generality in the access control to a web application we propose the use of roles and permissions associated to those roles. Thus, the access control to the functionalities will be done through the definition of permissions, and each role will have associated a series of permissions. The main advantage of this separation between roles and permissions is that the modification or creation of a role only will imply the association to this role to the corresponding permissions you wish grant to it.

If you use Spring Security 3.x to manage the security in your web application, you will have realize that this framework does not offer support for the concept of permissions, allowing only the definition of a series of roles, which can be associated to users. Spring Security carries out the access control checking if a concrete role has been asigned to a user. But it allows to define groups of roles. We will take advantage of this feature to implement the concept of permissions:
  • Users will change their associated roles for a group of roles. That group of roles will represent the concept of roles. e.g. ROLE_ADMIN, ROLE_CLIENT, etc.
  • A group of roles will be composed of a set of roles, which we will use to define the permissions. e.g. PR_CLIENT_REGISTER, PR_CLIENT_MODIFY, PR_STUFF_CREATE, etc.
For each feature we want to control its access, we will check if the user has the corresponding permission associated to any of its roles. 

@AuthorizeInstantiation(UserRolesAuthorizer.PR_EVENT_CREATE)
public class AddEvent extends BasePage {
...
}

Through the activation of the Spring Security annotations in the configuration:

<global-method-security secured-annotations="enabled" />

we can establish conditions at component level:

@PreAuthorize("hasRole('PR_EVENT_READ')")
public List getEvents() { ... } 

We also keep the traditional Spring Security roles (ROLE_ADMIN, ROLE_CLIENT, etc.) to define at this level the access control to certain elements.

To get all that, we defined a new user representation that extends the org.springframework.security.core.userdetails.UserDetails class and includes:
  • A list of the group of roles that has asociated the autenticated user account.
  • A list of all the permissions associated to all the roles that the user has.

References: