Flat Preloader Icon

Spring Security

Spring Security is a powerful framework for securing your Spring-based applications. It provides comprehensive security features for authentication, authorization, and protection against common security threats. In this tutorial, I’ll guide you through the basic steps to set up Spring Security in a Spring Boot application.
Step 1: Create a Spring Boot Application

Start by creating a new Spring Boot project or use an existing one. You can use the Spring Initializer (https://start.spring.io/) to generate a basic Spring Boot project with the necessary dependencies.
Step 2: Add Spring Security Dependency

In your project’s pom.xml (if using Maven) or build.gradle (if using Gradle), add the Spring Security dependency:
				
					<dependency>
    <groupId>org.springframework
    .boot</groupId>
    <artifactId>spring-boot
    -starter-security
    </artifactId>
</dependency>

				
			
				
					implementation 'org
.springframework.boot
:spring-boot-starter-security'

				
			
Step 3: Configure Spring Security

Create a Java class to configure Spring Security. This class should extend WebSecurityConfigurerAdapter and override the configure method to customize the security settings. For example, you can configure HTTP security, authentication providers, and access control rules.
				
					import org.springframework.context
.annotation.Bean;
import org.springframework.context
.annotation.Configuration;
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;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends 
WebSecurityConfigurerAdapter {

    @Override
    protected void configure
    (HttpSecurity http) 
    throws Exception {
       http
.authorizeRequests()
.antMatchers("/", "/home").permitAll(
// Publicly accessible pages
.anyRequest().authenticated()
.and().formLogin()
    .loginPage("/login") 
    // Custom login page
    .permitAll()
    .and()
    .logout()
        .permitAll();
    }

    @Bean
public PasswordEncoder 
passwordEncoder() {
 return new BCryptPasswordEncoder();
    }
}

				
			
In this example, we configure Spring Security to allow public access to the home page and require authentication for all other pages. We also define a custom login page and permit all users to access it.
Step 4: Create a Login Page

Create a login page (e.g., login.html or login.jsp) where users can enter their credentials. You can use Thymeleaf, JSP, or any other view technology of your choice. Ensure that the form action points to the /login URL, as Spring Security provides a built-in login processing URL.
Step 5: Configure User Authentication

You can configure user authentication by providing your own UserDetailsService implementation. This service retrieves user details (including username and password) from your data source (e.g., a database). You can also use an in-memory user store for testing purposes. Here’s an example:
				
					import org.springframework.beans.factory
.annotation.Autowired;
import org.springframework.context
.annotation.Bean;
import org.springframework
.context.annotation
.Configuration;
import org.springframework
.security.config.annotation
.authentication.builders
.AuthenticationManagerBuilder;
import org.springframework.security.core
.userdetails.User;
import org.springframework.security.core
.userdetails.UserDetails;
import org.springframework.security.core
.userdetails.UserDetailsService;
import org.springframework
.security.crypto.password
.PasswordEncoder;

@Configuration
public class SecurityConfig extends 
WebSecurityConfigurerAdapter {

    @Autowired
private PasswordEncoder 
passwordEncoder;

    @Override
protected void configure
    (AuthenticationManagerBuilder 
    auth) throws Exception {
        auth
.inMemoryAuthentication()
 .withUser("user")
.password(passwordEncoder()
.encode("password"))
.roles("USER");
    }

    @Bean
public PasswordEncoder 
passwordEncoder() {
return new 
BCryptPasswordEncoder();
    }
}

				
			
In this example, we configure an in-memory user store with a single user (user/password) having the USER role. In a real application, you would replace this with your database-backed user service.
Step 6: Implement Logout

If needed, create a logout link in your application and configure Spring Security to handle logout requests. For example:
				
					<a th:href="@{/logout}">
    Logout</a>

				
			
Step 7: Test Your Application:

Run your Spring Boot application and access the login page. Log in with the username and password configured in the configure method. You should be able to access authenticated resources based on your configuration.
This is a basic Spring Security setup. You can expand on this foundation by implementing more advanced features like role-based access control, CSRF protection, custom authentication providers, and securing RESTful APIs. Spring Security offers a wide range of features to address various security requirements in your application.

Share on: