Spring Security Tutorial: Authorization and user roles

11112014

User authenticated with username and password can access web pages. The second step is to authorize him – decide whether or not he is authorized to access certain resources or not. Spring supports role based authorization. In this tutorial I will show how to assign users a role and how to authorize them.

Use case scenarios

In simpliest case, you can have one role and allow it to access all of your views, or few roles, each authorized to only a subset of resources. For example you can have users with role ‘USER’ that are app users, and ‘ADMIN’ which have more rights and access to admin resources in your webapp.

In the code base you have a method to authenticate user. There is an Autowired configureGlobal() method in a WebSecurityConfigurerAdapter. In it I use the simplest, default in memory authentication, verifying user’s login, password and assigning him a role ‘USER‘:

Now when you have two user roles, you can specify wich role will have access to certain resource. In my app I have the hello page and greeting page. I will permit ADMIN role to both of these resources, and USER role only to hello page. Moreover I will require any request to be authenticated, so user must log in. This is how these rules look like in implementation:

After logging in, you will also be redirected to the Welcome page, but when you click th link on that page, you will get the Error Page 403, which means that you are not authorized to access it.

5. Provide custom unauthorized page

The spring’s Whitelabel error page is not the best you can have in your app, so let’s configure new template to have nice, custom unauthorized message for your users. To do it, you just create new html template and controller, let’s name it ‘unauthorized’ and add the exception configuration for HttpSecurity in configure method:

Did I help you?
I manage this blog and share my knowledge for free, sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality