SoFunction
Updated on 2025-03-06

Detailed steps to quickly integrate SpringBoot (newcomers can do it!)

1. What is SpringSecurity?

Spring Security is a security framework based on the Spring framework, providing a set of lightweight APIs and tools for implementing common security features such as authentication, authorization, and attack prevention. It supports various authentication methods such as basic authentication, form authentication, OAuth2.0 and OpenID Connect. Spring Security also offers a number of configurable options that allow developers to customize according to the needs of the application. Spring Security has become one of the most widely used security frameworks in Java enterprise-level applications.

2. The principle of SpringSecurity

The core principle of Spring Security is to protect application resources based on Filter Chain. In this filter chain, different filters are responsible for different security functions such as authentication, authorization, attack defense, etc.

When a request reaches the application, it is first intercepted by the outermost filter. This filter passes the request to the next filter and continues to perform some pre-processing (such as logging, cross-domain request processing, etc.). Next, each filter in the filter chain will handle its own processing until the request is processed by the innermost filter and returns the response.

Spring Security protects application resources by configuring filter chains. Each filter has different responsibilities, such as:

(1) AuthenticationFilter: an authentication filter, used to authenticate users.

(2) AuthorizationFilter: Authorization filter, used to check whether the user has permission to access a resource.

(3) CsrfFilter: Prevent cross-site request forgery (CSRF) filters, used to prevent CSRF attacks.

(4) ExceptionTranslationFilter: Exception conversion filter, used to handle safety-related exceptions.

(5) SessionManagementFilter: Session Management Filter, used to manage user sessions.

Developers can customize their own security policies based on the APIs and tools provided by Spring Security and add them to the filter chain. This way, when the application receives a request, it follows these security policies to protect the application resources.

3. SpringBoot integrates SpringSecurity

Add dependencies

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Configuring Spring Security

# Set the default user=user
=pass

# Turn off CSRF protection=false

Write security configuration classes. Write a security configuration class to configure Spring Security. This class should extend WebSecurityConfigurerAdapter and override some methods to configure security.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    // Configure user information    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        ()
            .withUser("user").password("{noop}pass").roles("USER");
    }
    
    // Configure HTTP request security    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ()
            .antMatchers("/public/**").permitAll() // Allow all requests under /public/** path            .anyRequest().authenticated() // All other requests require authentication            .and()
            .formLogin() // Enable form login            .loginPage("/login") // Specify the login page            .defaultSuccessUrl("/", true) // Redirect to the home page after login is successful            .permitAll() // Allow all users to access the login page            .and()
            .logout() // Enable logout            .logoutUrl("/logout") // Log out the URL            .logoutSuccessUrl("/login") // Redirect to the login page after logging out successfully            .permitAll(); // Allow all users to log out    }
}

In the above configuration, we configured a memory authentication (using username and password) and HTTP request security (allowing requests under certain paths, requiring all other requests to require authentication, and enabling form login and logout).

Writing a controller. Finally, you need to write a controller to handle login and logout requests.

@Controller
public class LoginController {
    
    // Process login request    @GetMapping("/login")
    public String login() {
        return "login";
    }
    
    // Process the logout request    @PostMapping("/logout")
    public String logout() {
        return "redirect:/login?logout=true";
    }
}

In the above code, we define a login() method to handle login page requests and return a template named login. The logout() method is used to process the logout request and redirect to the login page.

Write html template. Finally, we need to write a template called to render the login page.

<!DOCTYPE html>
<html>
<head>
    <title>Login</title>
</head>
<body>
    <h1>Login</h1>
    <form action="/login" method="post">
        <div>
            <label for="username">Username:</label>
            <input type="text"  name="username" required autofocus />
        </div>
    </form>
</body>
</html>

Summarize

This is the article about the detailed steps of SpringBoot's rapid integration of SpringSecurity. For more relevant SpringBoot's rapid integration of SpringSecurity, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!