Home » Framework » How to configure Authorization in Spring Boot Security

How to configure Authorization in Spring Boot Security

Authorization is the security process in which user is allowed to access the services based on their roles and authorities. Simply say it asks the question like can this user accessible this?. (or) can this user allowed to do this?.

In this article, we are going to see how to configure the authorization of Spring Security in the Spring Boot Application. The below are the steps need to do for configuring authorization in Spring Security

  1. Need to create the Spring Boot Project with "spring-boot-starter-security" as a dependency.
  2. Configure Authentication and store some hard-coded users in in-memory.
  3. Need to create some of the APIs which is specifically accessible by particular roles of users.
  4. Configure authorization by overriding configure method which takes HttpSecurity as an argument.

Steps 1 & 2 we have already seen in the previous article. If you want to know about please click here Spring Boot Security Authentication. Now let start to see step 3 & 4.

We need to create some of the APIs first in "HomeController" which is specifically accessible by some roles of users like below.

package com.tipstocode.SpringBootSecurity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {	
	@GetMapping("/")
	public String login(){
		return "Welcome to TipsToCode Site!";
	}	
	@GetMapping("/user")
	public String user(){
		return "Welcome user to TipsToCode Site!";
	}	
	@GetMapping("/admin")
	public String admin(){
		return "Welcome admin to TipsToCode Site!";
	}
}

Configure Authorization in Spring Security

Now, let's start to see the configuration of authorization in Spring Boot. For that, we have to override the configure method which takes HttpSecurity as an argument in Security configuration.

In the last article, we have configured authentication right!. In the same way, we have to do it for authorization also. Both the configurations are below.

//Authentication Configuration
@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception{		
		
	}
//Authorization Configuration
@Override
	protected void configure(HttpSecurity http) throws Exception{
		
	}

Now let start to configure some of the endpoints / URL's can be accessible by only some roles of users. Look at the below table which shows the URLs with the access of particular roles of users.

URL's / EndpointsAccessible by Roles of Users
/All Users
/userUSER and ADMIN Role
/adminonly ADMIN Role.

we already created all the three endpoints mentioned in the table above in "HomeController". By default, all the endpoints are authenticated in Spring Security. But here we are going to configure the URL's which is accessible only by particular roles of users by using Authorization.

The below snippet is the complete configuration of Authorization.

package com.tipstocode.SpringBootSecurity;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{	
	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception{		
		auth.inMemoryAuthentication()
		.withUser("user")
		.password("password")
		.roles("USER")
		.and()
		.withUser("admin")
		.password("password")
		.roles("ADMIN");		
	}	
	@Bean
	public PasswordEncoder getPasswordEncoder(){
		return NoOpPasswordEncoder.getInstance();
	}	
	@Override
	protected void configure(HttpSecurity http) throws Exception{		
		http.authorizeRequests()
			.antMatchers("/admin").hasRole("ADMIN")
			.antMatchers("/user").hasAnyRole("USER", "ADMIN")
			.antMatchers("/").permitAll()
			.and().formLogin();
	}
}

We can do the restrict access to endpoints with the help of http.authorizeRequests() method chaining. We have to specify the path (or) URL in antMatchers() method and we have to specify the roles in hasRole() or hasAnyRole() method.

In hasRole() method we can specify only one role and in hasAnyRole() method we can specify the 'n' number of roles.

In the above configuration what we did is the URL '/' accessible by all users and the URL '/admin' accessible by the role of ADMIN users and the URL '/user' accessible by the role of USER and ADMIN users.

There are several types of login available in Spring Security. But the most popular one is form login. So I have added form login as the login type at the end of the method chaining.

The most important thing is we have to specify the access restrictions order-wise. The order should be most restrictive to least restrictive. For example, in the above configuration, 'ADMIN' is the most restrictive and the least restrictive is '/' which is accessible by all unauthenticated users.

So we have to specify 'ADMIN' as the top then followed by 'USER' and then followed by "/" in the method chaining. If we mention "/" at the top then all the users can be accessible by any endpoints irrespective of roles.

Now, let's run the application and test that in the browser.

If you access the URL "http://localhost:8080/" then you will see the message in a browser like 'Welcome to TipsToCode Site!'. Because this is the base URL there is no authentication or authorization needed.

If you access the endpoint "http://localhost:8080/user" then it shows the login screen in the browser to authenticate. you have to put either user credentials or admin credentials to access this.

Spring-Security-User-Login

Please enter the user name and password of any user or admin role which is mentioned in the authentication part in Security Configuration. Once authenticated successfully then you will see a message in the browser like "Welcome user to TipsToCode Site!".

Likewise, the endpoint "http://localhost:8080/admin" needs authentication with the role of only 'ADMIN' users. The users who are having the role of 'ADMIN' can only access this endpoint.

Hope you understood how to configure the authorization of Spring Security in the Spring Boot Application. In the next article, we will see how authentication works in Spring Security in a detailed view. Thanks!. Keep Reading!.

2 thoughts on “How to configure Authorization in Spring Boot Security

  1. you are truly a excellent webmaster. The website loading pace is amazing.
    In addition, The contents are masterwork. you've done a great activity on this topic!

Leave a Reply

Your email address will not be published. Required fields are marked *