Open In App

Spring Security – Custom Login

Improve
Improve
Like Article
Like
Save
Share
Report

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:

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

SpringSecurity provides its own login configuration with the default user name and the password but we can override the default configuration of SpringSecurity by creating a custom login configuration. We can add multiple users and also we can allow them different roles. So that we can perform Authorisation on the secured API easily. Let’s discuss how to create a custom login in Spring Security.

Step by Step Implementation

Step 1: Create a Spring Boot project using https://start.spring.io/

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

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: This config file is used for creating custom security in the Spring project.

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:

Output:

Using the student role:

Output:

This way we can create a custom login in the Spring Application. 



Last Updated : 30 Dec, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads