Open In App

Spring Security Project Example using Java Configuration

Last Updated : 08 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Spring Security is a standard for security in spring-based applications, it provides authentication as well as authorization to the application. Spring Security is a powerful tool that provides the feature of custom security configuration to the user, security configuration in spring can be customized in two ways as listed below as follows: 

  1. XML-based configuration
  2. Java configuration.

Here we will be creating a login form using a custom java-based security configuration and adding authentication and authorization to our application.

Prerequisites:  Introduction to spring, spring boot

Steps to Create a Java-Based Security Form

Step 1: Create a Spring boot project using spring initializr and provide a Group and an Artifact Id, choose the spring boot version, add Spring Web, Spring Security, and Thymeleaf as the dependencies.

Step 2: Extract the downloaded file and import it into Eclipse as Maven project, the project structure would look something like this:

The created project should have a pom.xml where the configuration and all the dependencies are defined. We’re using spring boot so we don’t need to define anything extra right now.

File: pom.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.gfg</groupId>
    <artifactId>SpringSecurityJavaConfig</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>SpringSecurityJavaConfig</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
 
</project>


This class is responsible to build everything up and run your spring boot application.

Java




// Java program to Illustrate Configuration Java Application
// In Spring Security
 
package com.gfg.SpringSecurityJavaConfig;
 
// Importing required classes
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
// Annotation
@SpringBootApplication
// Class
public class SpringSecurityJavaConfigApplication {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        SpringApplication.run(
            SpringSecurityJavaConfigApplication.class,
            args);
    }
}


 
 

Code Explanation: The Controller class handles the incoming requests by redirecting them to the appropriate view page, any URL must be defined in the controller class in order to send a request. The LoginController class is present in the com.gfg.SpringSecurityJavaConfig.controller package has four method for mapping to four different view pages. All these view pages are accessible according to the role of the user. Now, let’s see how to define different roles for different users.

 

Java




// Java Program to Illustrate LoginController Class
 
package com.gfg.SpringSecurityJavaConfig.cotroller;
 
// Importing required classes
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
 
// Annotation
@Controller
// Class
public class LoginController {
 
    @GetMapping("/welcome") public String welcome()
    {
        return "welcome.html";
    }
 
    @GetMapping("/admin") public String user()
    {
        return "admin.html";
    }
 
    @GetMapping("/basic") public String basic()
    {
        return "basic.html";
    }
 
    @GetMapping("/login") public String login()
    {
        return "login.html";
    }
}


 
 

Code Explanation: 

 

  • The SpringSecurityConfig class in the com.gfg.SpringSecurityJavaConfig.security package is where the configuration of your spring security is defined. This class extends the WebSecurityConfigureAdapter class which provides methods like configure to add custom authentication and authorization for the user.
  • The first configure method has the parameter of AuthenticationManagerBuilder which defines the authentication of the user. We’ll use a hard-coded user id and password for simplicity.
  • The passwordEncoder encrypts the password using BCryptPasswordEncoder.
  • The second configure method defines the authorization for the user, it defines the mapping for a user with a particular role, as you can see we have defined that all the users with roles “BASIC” are allowed to access only the welcome and basic page whereas the user with role “ADMIN” is allowed to access all the URLs. We have also defined a custom login page which will be the redirect point of any URL requested.

 

Java




// Java Program to Illustrate Spring Security
 
package com.gfg.SpringSecurityJavaConfig.security;
 
// Importing required classes
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.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
 
// Annotation
@EnableWebSecurity
// Class
public class SpringSecurityConfig
    extends WebSecurityConfigurerAdapter {
 
    // Annotation
    @Override
    protected void
    configure(AuthenticationManagerBuilder auth)
        throws Exception
    {
        auth.inMemoryAuthentication()
            .passwordEncoder(passwordEncoder())
            .withUser("gfg")
            .password(passwordEncoder().encode("pass"))
            .roles("ADMIN")
            .and()
            .passwordEncoder(passwordEncoder())
            .withUser("user")
            .password(passwordEncoder().encode("pass"))
            .roles("BASIC");
    }
 
    // Annotation
    @Bean
    // Method
    public PasswordEncoder passwordEncoder()
    {
        return new BCryptPasswordEncoder();
    }
 
    // Annotation
    @Override
    // Method
    protected void configure(HttpSecurity http)
        throws Exception
    {
 
        http.authorizeRequests()
            .antMatchers("/basic")
            .hasAnyRole("BASIC", "ADMIN")
            .antMatchers("/admin")
            .hasRole("ADMIN")
            .antMatchers("/")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .formLogin()
            .permitAll()
            .loginPage("/login")
            .usernameParameter("username")
            .and()
            .logout()
            .logoutRequestMatcher(
                new AntPathRequestMatcher("/logout"))
            .permitAll();
    }
}


 
 

This is the login.html page in the templates folder, it defines the login page for the application.

 

File: login.html

 

HTML




<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>Login page</h1>
    <form th:action="@{/login}" method="post">
        <div><label>Username: </label><input type="text" name="username"></div>
        <div><label>Password: </label><input type="password" name="password"></div>
        <div><button name="submit" type="submit" >Login</button></div>
    </form>
</body>
</html>


 
 

This is the welcome.html page accessible to all the users with any role.

 

File: welcome.html

 

HTML




<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h1>LoggedIn Successful</h1>
    <h2>Welcome Back Click here to <a href="logout">logout</a></h2>
</body>
</html>


 
 

This is the basic.html page accessible to “BASIC” as well as “ADMIN” users.

 

File: basic.html

 

HTML




<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>basic page</title>
</head>
<body>
    <h1>Welcome Basic User</h1>
</body>
</html>


 
 

This is the admin.html page accessible to only the users with the “ADMIN” role.

 

File: admin.html

 

HTML




<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Admin page</title>
</head>
<body>
    <h1>Welcome Admin</h1>
</body>
</html>


 
 

Step 3: After adding all the classes and the view pages our project structure looks something like this:

 

 

Step 4: Now it’s time to run your application, after running your application type this URL in any of browser http://localhost:8080/SpringSecurityJavaConfig/welcome.

 

 

So we have created a spring security web application using java based configuration and added custom authentication and authorization to our application.

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads