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.
Let’s first discuss the basic simple authentication of Spring Security. In Simple authentication, Spring Security provides a default user name and the password that we have to use for valid authentication.
XML
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-security</ artifactId > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-web</ artifactId > </ dependency > |
Login page of simple authentication of Spring Security:
Password:
It is very difficult to remember this password because this is a random password and Spring Security generates a random password every time when we execute the Spring Application. If we want to add a custom user name and password in the Spring application for authentication we can add it easily(using application.properties ) but if we want to make our Spring application for multiple users it is difficult to configure their credentials. So to overcome this situation when we handle multiple authentications along with their respective roles. We will use in-memory authentication in the Spring Application.
in-memory authentication is the way for handling authentication in Spring Security. In the in-memory authentication we hardcore all the user details such as roles, passwords, and the user name. We can perform validation until the Spring server is running. If the server is stopped the memory is cleared out and we cannot perform validation. This is the main drawback of in-memory authentication.
inMemoryAuthentication() is the method of AuthenticationManagerBuilder class is used to perform in-memory authentication in the Spring Security. This method is used for creating the user with respective roles and passwords. Let’s discuss how to implement inmemoryAuthentication in Spring Security.
Step by Step Implementation
Step 1: Create a Spring Boot Project
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.
Project Structure:
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 extending the WebSecurityConfigureAdapter class and we override two methods configure(AuthenticationManagerBuilder auth) and configure(HttpSecurity Http) both methods are used for handling the multiple authentications on the Spring application.
- The first method is used for adding the credentials of the users with respective roles in the inMemory of SpringApplication.
- The second method is used for handling the user-defined API in the Spring application.
Java
package com.example.SpringBootApp; 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 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( "GFG" ) .password( "Helloword" ) .roles( "student" ); } // Configuring the api // according to the roles. @Override protected void configure(HttpSecurity http) throws Exception { http. httpBasic() .and() .authorizeRequests() .antMatchers( "/delete" ).hasRole( "admin_role" ) .antMatchers( "/details" ).hasAnyRole( "admin_role" , "student" ) .and() .formLogin(); } // Function to encode the password // assign to the particular roles. @Bean public PasswordEncoder getPasswordEncoder(){ return NoOpPasswordEncoder.getInstance(); } } |
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: Try to access the details API using the student role’s user name and password.