Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Spring – Add Roles in Spring Security

  • Last Updated : 26 Nov, 2021

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is found in how easily it can be extended to meet custom requirements. Some of the key features of Spring Security are:

  1. Comprehensive and extensible support for both Authentication and Authorization
  2. Protection against attacks like session fixation, clickjacking, cross-site request forgery, etc
  3. Servlet API integration
  4. Optional integration with Spring Web MVC

In this article, we will discuss how to add roles in spring security. In almost every web application the first step we do authentication that is the first major step for everyone who wants to access the web application but considers an application of university in which students, as well as teachers, are using that website. All the teachers have extra access like they can delete the record of the particular student records but the student cannot able to do that. Now think about how this is possible? This is possible only when they differ on the roles /delete request can be made only the high priority roles, not by the lower priority roles. In this case, students are set to be low priority roles whereas teachers are on the top priorities roles. Let’s discuss how to add roles in the spring web application.

Step by Step Implementation

Step 1: Go to Spring Initializr

Fill in the details as per the requirements. For this application:

Project: Maven
Language: Java
Spring Boot: 2.2.8
Packaging: JAR
Java: 8
Dependencies: Spring Web

Step 2: Click on Generate which will download the starter project.

Step 3: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:

Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project.

Step 4: Now go to the src > main > java > com.gfg.Spring.boot.app and create two java files one is controller.java and the other is config.java

controller.java

Java




@RestController
public class controller {
  
    @GetMapping("/delete") public String delete()
    {
        return "This is the delete request";
    }
}

The above java file is used to set the controller for handling the incoming request from the client-side. Now we have to configure the request for that we will use the config.java file.



config.java

Java




@EnableWebSecurity
public class config extends WebSecurityConfigurerAdapter {
  
    // Adding the roles
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("Zack")
                .password("aayush")
                .roles("admin_role")
                .and()
                .withUser("Aayush")
                .password("Saini")
                .roles("student_role");
    }
    
    // Configuring the api 
      // according to the roles.
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.
                httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers("/delete").hasRole("admin_role")
                .and()
                .formLogin();
    }
    
      // Function to encode the password
      // assign to the particular roles.
    @Bean
    public PasswordEncoder getPasswordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }
}

The WebSecurityConfigureAdapter class is used for configuration the incoming requests mainly two methods are used for configurations. The first method is used for adding the roles for a spring application server and the other method is used to distinguish the request according to the roles. Now run the main application of the spring application

Note: There is no default password is generated because we have already used external configuration for handling the user credentials.

Testing the API in Postman

Go to the postman and type localhost:8080/delete

Using the admin roles:

Using the student role:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!