Spring Boot in Memory Basic Authentication Example
Welcome readers, in this tutorial, we will implement the security mechanism with in-memory authentication in a spring boot application.
1. Introduction
- Spring Boot is a module that provides rapid application development feature to the spring framework including auto-configuration, standalone-code, and production-ready code
- It creates applications that are packaged as jar and are directly started using embedded servlet container (such as Tomcat, Jetty or Undertow). Thus, no need to deploy the war files
- It simplifies the maven configuration by providing the starter template and helps to resolve the dependency conflicts. It automatically identifies the required dependencies and imports them in the application
- It helps in removing the boilerplate code, extra annotations, and xml configurations
- It provides a powerful batch processing and manages the rest endpoints
- It provides an efficient jpa-starter library to effectively connect the application with the relational databases
Now, open the eclipse ide and let’s see how to implement this tutorial in spring boot.
2. Spring Boot in Memory Basic Authentication Example
Here is a systematic guide for implementing this tutorial.
2.1 Tools Used
We are using Eclipse Kepler SR2, JDK 8, and Maven.
2.2 Project Structure
In case you are confused about where you should create the corresponding files or folder, let us review the project structure of the spring boot application.
2.3 Project Creation
This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project
.
In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Just click on the next button to proceed.
Select the Maven Web App archetype from the list of options and click next.
It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT
.
Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml
file will be created. It will have the following code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.springboot.authentication</groupId> <artifactId>Springbootinmemoryauthtutorial</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> </project>
Let’s start building the application!
3. Creating a Spring Boot application
Below are the steps involved in developing the application.
3.1 Maven Dependencies
Here, we specify the dependencies for the Spring Boot and Security. Maven will automatically resolve the other dependencies. The updated file will have the following code.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.springboot.authentication</groupId> <artifactId>Springbootinmemoryauthtutorial</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>Springboot inmemory authentication tutorial</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.RELEASE</version> </parent> <dependencies> <!-- spring boot web mvc dependency. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- spring boot security dependency. --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> </dependencies> <build> <finalName>Springbootinmemoryauthtutorial</finalName> </build> </project>
3.2 Application Properties
Create a new properties file at the location: Springbootinmemoryauthtutorial/src/main/resources/
and add the following code to it.
application.properties
# Application configuration. server.port=8102
3.3 Java Classes
Let’s write all the java classes involved in this application.
3.3.1 Implementation/Main class
Add the following code the main class to bootstrap the application from the main method. Always remember, the entry point of the spring boot application is the class containing @SpringBootApplication
annotation and the static main method.
Myapplication.java
package com.springboot.auth.inmemory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * Main implementation class which serves two purpose in a spring boot application: Configuration and bootstrapping. * @author yatin-batra */ @SpringBootApplication public class Myapplication { public static void main(String[] args) { SpringApplication.run(Myapplication.class, args); } }
3.3.2 Security Configuration class
Let us include the following code to this class to secure the urls and handle the in-memory authentication.
Securityconfig.java
package com.springboot.auth.inmemory.config; import org.springframework.context.annotation.Configuration; 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; //Spring boot security configuration class. @Configuration @EnableWebSecurity // Enables security for our application. public class Securityconfig extends WebSecurityConfigurerAdapter { // Securing the urls and allowing role-based access to these urls. @Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic().and().authorizeRequests() .antMatchers("/security/guest").hasRole("USER") .antMatchers("/security/admin").hasRole("ADMIN") .and().csrf().disable(); } // In-memory authentication to authenticate the user i.e. the user credentials are stored in the memory. @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().withUser("guest").password("{noop}guest1234").roles("USER"); auth.inMemoryAuthentication().withUser("admin").password("{noop}admin1234").roles("ADMIN"); } }
3.3.3 Controller class
Let us include the following code to the controller class.
Mycontroller.java
package com.springboot.auth.inmemory.controller; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping(value= "/security") public class Mycontroller { // Method to serve the guest page! @GetMapping(value= "/guest") public ResponseEntity<String> guest() { System.out.println("Showing guest page."); return new ResponseEntity<String>("Hello from guest page!", HttpStatus.OK); } // Method to serve the secure/administration page! @GetMapping(value= "/admin") public ResponseEntity<String> admin() { System.out.println("Showing administrator page."); return new ResponseEntity<String>("Welcome to secure/admin page!", HttpStatus.OK); } }
4. Run the Application
As we are ready with all the changes, let us compile the spring boot project and run the application as a java project. Right click on the Myapplication.java
class, Run As -> Java Application
.
5. Project Demo
Open the postman tool and hit the following urls to display the data in the json format.
SECURE PAGE Url - http://localhost:8102/security/admin GUEST PAGE Url - http://localhost:8102/security/guest
Make a note to enter the valid login credentials in the postman requests for getting the valid results. If the login credentials are missing or incorrect, the users will get a 403 error. That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!
6. Conclusion
In this section, developers learned how to create an in-memory authentication mechanism in a spring boot application. Developers can download the sample application as an Eclipse project in the Downloads section.
7. Download the Eclipse Project
This was an example of configuring the In-memory authentication in a Spring Boot application.
You can download the full source code of this example here: Spring Boot in Memory Basic Authentication Example
i tried the above example.but getting Your login attempt was not successful, try again.
Reason: Bad credentials
U may pass wrong value . please provide “key”: “password”,
“value”: “admin1234”, – > pwd
“type”: “string”
},
{
“key”: “username”,
“value”: “admin”, – user name
“type”: “string”
}