Open In App

Spring Security - How to Add and Manage Roles in Your Application

Last Updated : 28 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Spring Security is a powerful and highly customizable authentication and access-control framework. Security is an important thing when dealing with DELETE requests that modify or remove resources. Spring Security provides a robust way to secure endpoints using basic authentication. This ensures only authorized users can access sensitive APIs. In this article, we will explore how to secure a DELETE request in a Spring Boot application, using role-based access control with Spring Security. By following this article, we will,

  • Implement Basic Authentication in Spring Boot.
  • Restrict access to DELETE endpoints using role-based authorization.
  • Test the secured API using Postman.

Step by Step Implementation

Step 1: Create a Spring Boot Project

Go to Spring Initializr and fill in the required details:

Project: Maven
Language: Java
Spring Boot: 3.x.x (Latest stable version)
Packaging: JAR
Java: 17 or latest
Dependencies: Spring Web, Spring Security

Spring-Initializr


Click Generate, download the project ZIP, and extract it.

Step 2: Import the Project into Your IDE

  • Open your preferred IDE (IntelliJ IDEA, Eclipse, VS Code, etc.).
  • Go to File > New > Project from Existing Sources.
  • Select the pom.xml file from the extracted folder.
  • Click Import Changes when prompted.

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 3: Create Controller and Configuration Files

Now, navigate to src/main/java/com/gfg/spring/boot/app and create two Java files:

  • Controller.java: Handles incoming requests.
  • Config.java: Configures Spring Security.

Step 4: Implement the Controller Class

Create a new Java file Controller.java inside your project:

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. This controller defines a "/delete" endpoint that will later be protected by role-based authentication.

Step 5: Configure Spring Security

Create a new Java file Config.java to define authentication and authorization rules.

Java
@EnableWebSecurity
public class Config extends WebSecurityConfigurerAdapter {

    // Defining users and their roles
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("Zack")
                .password("aayush")
                .roles("ADMIN")
                .and()
                .withUser("Aayush")
                .password("Saini")
                .roles("STUDENT");
    }

    // Securing APIs based on roles
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers("/delete").hasRole("ADMIN")
                .and()
                .formLogin();
    }

    // Password encoder for storing plain-text passwords 
    // (Not recommended for production)
    @Bean
    public PasswordEncoder getPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}

Explanation:

  • User Authentication: Two users are defined - "Zack" (ADMIN) and "Aayush" (STUDENT).
  • Role-Based Authorization: Only users with the ADMIN role can access the /delete endpoint.
  • Password Encoding: NoOpPasswordEncoder is used for simplicity (avoid in production).

Step 6: Run the Spring Boot Application

Run the main application class in your IDE to start the Spring Boot project.

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

Step 7: Testing the API in Postman

Now, let's test the secured API using Postman:

Open Postman and enter the URL:

http://localhost:8080/delete

Select Basic Auth and enter the credentials:

  • Username: Zack
  • Password: aayush

Click Send.

If the user has the ADMIN role, the response will be:


Using the student role:

If the user does not have the required role, a 403 Forbidden error will be returned.


SecurityFilterChain in Spring Security 5+

Starting from Spring Security 5.7, WebSecurityConfigurerAdapter has been deprecated, and SecurityFilterChain is the recommended approach for configuring security. Instead of overriding configure() methods, we now define a SecurityFilterChain bean.

If you are using the latest Spring Security version, your config.java file should be updated as follows:

Java
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .httpBasic()
            .and()
            .authorizeHttpRequests()
            .antMatchers("/delete").hasRole("ADMIN")
            .anyRequest().authenticated()
            .and()
            .formLogin();
        return http.build();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        UserDetails admin = User.withDefaultPasswordEncoder()
                .username("Zack")
                .password("aayush")
                .roles("ADMIN")
                .build();

        UserDetails student = User.withDefaultPasswordEncoder()
                .username("Aayush")
                .password("Saini")
                .roles("STUDENT")
                .build();

        return new InMemoryUserDetailsManager(admin, student);
    }
}

This new approach provides better flexibility and aligns with the latest Spring Security practices. But, our existing implementation with WebSecurityConfigurerAdapter will still work in Spring Boot 3, but it is advisable to migrate to SecurityFilterChain in the future.


Next Article
Practice Tags :

Similar Reads