Roles & Permissions with Spring-Security 3

The Spring-Security approach to model roles and permissions is, in my opinion, very strange. In fact, out of the box you have either an overly simple approach with just users and roles, or a very complex heavy weigh approach with security on every domain object instance.

The most common requirement for security that I come across is that you want to have 3 types:

Users – which represents a user who can logon into a system

Roles – which consists of several users and several permissions

Permissions – which defines fine-granular access rights in the system

With these 3 types you can handle the most of the security challenges and at the same time it’s not an overly-complicated model.

In this tutorial I want to show you how to apply this approach to spring-security.

Requirements

You should be familiar with spring in general and spring dependeny injection

Database

You have to create 5 tables in a database of your choice to implement the described security model. In the following I will provide scripts to generate the tables in MySQL, but you can adjust the scripts to fit your database. You need the following tables:

Spring Configuration

To tell spring that it should use the new security model, you have to implement a custom authentication-provider. To do this, you need to extend the spring class JdbcDaoImpl. At the moment it is sufficient to just implement an empty class here:

Now in the spring configuration you can add the custom authentication provider and the newly created SpringSecurityDaoImpl. The authentication provider has a property groupAuthoritiesByUsernameQuery. You can use this property to provide an sql that retrieves the permissions of a user from the database.

Using the security model

Now it is possible with spring to check if a user has a certain permission. Therefore you can use the common annotations provided by spring e.g. @PreAuthorize. Let’s say you want to check if a user has the permission to list products, you would have a permission readProducts in the permission table. You can now check if the user has the permission in your java code with: