Spring Security Tutorial: Authorization and user roles

11 11 2014

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.

Download the source code

Full source code for this tutorial is available for download on my git: https://github.com/yacekmm/looksok/tree/RoleBasedAccessTutorial/Spring/SpringSecurity

1. Get the code base

This tutorial is based on the code developed in my previous tutorial. Download the code or follow the tutorial in: Spring Security: Securing your MVC app with basic login and password authentication.

2. What we have now

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 roleUSER‘:

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
    auth
      .inMemoryAuthentication()
        .withUser("user").password("userPwd").roles("USER");
  }
}

If you are loking for custom authentication method, take a look at the Spring Security Tutorial: Custom authentication engine.

2. Add user with Admin role

Now we want to add the new user with ADMIN role. This is as simple as duplicating the line in previous snippet. My configureGlobal method now is as follows:

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
  auth
    .inMemoryAuthentication()
      .withUser("user").password("userPwd").roles("USER")
      .and()
      .withUser("admin").password("adminPwd").roles("ADMIN");
}

3. Implement role based access

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:

protected void configure(HttpSecurity http) throws Exception{

  http
    .formLogin().permitAll()
  .and()
    .authorizeRequests()
    .antMatchers("/hello").hasRole("USER")
    .antMatchers("/hello", "/greeting").hasRole("ADMIN")
    .anyRequest().authenticated();
}

4. Run App and verify

Start the spring boot app and go to the url:

http://localhost:8080/

You will be automatically redirected to the login page. Login as admin:

admin :  adminPwd

after login you will be redirected to Welcome page (hello), and when you click a link, you will be redirected to the greeting page.

Now logout by going to the login page in your app with logout param:

http://localhost:8080/login?logout

And login as user:

user :  userPwd

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:

.and()
  .exceptionHandling().accessDeniedPage("/unauthorized");

Download the source code

Full source code for this tutorial is available for download on my git: https://github.com/yacekmm/looksok/tree/RoleBasedAccessTutorial/Spring/SpringSecurity

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

Donate Button with Credit Cards

Thank You!

Advertisements

Actions

Information

2 responses

24 06 2015
Sophia German

Thank you for this post, helped me a lot

23 07 2016
Spring: Securing REST API with BasicAuth | Looks OK!

[…] in one of my previous tutorials (Spring Security Tutorial: Authorization and user roles), you need to extend the […]

Give Your feedback:

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: