SoFunction
Updated on 2025-03-08

SpringBoot uses Sa-Token to implement path interception and specific interface release

1. Introduce dependencies

First, inThe Sa-Token-related dependencies are introduced into the file. Sa-Token is a lightweight Java permission authentication framework that can help us easily manage user login status and permission authentication.

<dependency>
    <groupId>cn.dev33</groupId>
    <artifactId>sa-token-spring-boot-starter</artifactId>
    <version>1.27.0</version>
</dependency>

2. Create configuration class SecurityProperties

Define a configuration classSecurityProperties, used to read and store exclusion path information loaded from the configuration file. Spring Boot is used here@ConfigurationPropertiesAnnotation to bind properties in the configuration file.

import ;
import ;
import ;

@Data
@Component
@ConfigurationProperties(prefix = "security")
public class SecurityProperties {
    /**
      * Exclude paths
      */
    private String[] excludes;
}
  • @Data: This is Lombok's annotation, which automatically generates getter and setter methods.
  • @Component: Register this class as a component of Spring.
  • @ConfigurationProperties: Specify the prefixsecurity, read attributes starting with the prefix from the configuration file and map these attributes to fields in the class.

3. Write configuration files

In configuration fileor, configure the paths that need to be excluded. For example:

:

security:
  excludes:
    - "/public/**"
    - "/login"
    - "/register"

:

=/public/**,/login,/register
  • /public/**: Exclude all/public/The path to begin.
  • /login:exclude/loginpath.
  • /register:exclude/registerpath.

4. Configure the interceptor

Create a configuration classWebConfig,accomplishWebMvcConfigurerInterface where Sa-Token's interceptor is configured and the excluded path is applied to the interceptor.

import ;
import ;
import ;
import ;
import cn.;
import cn.;
import cn.;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private SecurityProperties securityProperties;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        (new SaInterceptor(handler -&gt; {
            // Get all URLs and check            ("/**").check(() -&gt; {
                // Check whether to log in                ();
            });
        }))
        .addPathPatterns("/**")  // Intercept all paths        .excludePathPatterns(());  // Exclude specified paths    }
}
  • @Configuration: Identify this is a configuration class.
  • addInterceptors: Rewrite this method and add a custom interceptor to Spring's Interceptor Registration Center.
  • SaInterceptor: Interceptor provided by Sa-Token, mainly used for permission verification.
  • ("/**"): Match all paths.
  • (): The login status check method provided by Sa-Token, used to verify whether the user is logged in.
  • excludePathPatterns: Exclude specified paths from intercept, fromSecurityPropertiesGet it in.

5. Verify the interception effect

Start the Spring Boot application and verify that the configuration is in effect. Here are some test steps:

  • Access exclusion path

    • Try to access the path excluded in the configuration file, such as/public/**/login/register
    • These paths should not trigger login checks and can be accessed directly.
  • Visit other paths

    • Try to access other unexcluded paths, such as/admin/user/profilewait.
    • These paths should trigger the login verification logic of Sa-Token. If the user is not logged in, it will be intercepted and the corresponding unlogin prompt will be returned.

Code parsing

  • SecurityPropertieskind:pass@ConfigurationPropertiesAnnotation, Spring Boot will automatically prefix it assecurityThe configuration properties of the class are bound toexcludesfield, thus implementing configuration of exclude paths.
  • Configuration File: Define paths to be excluded in the configuration file for dynamic loading toSecurityPropertiesmiddle.
  • WebConfigkind:accomplishWebMvcConfigurerInterface, throughaddInterceptorsMethods to add Sa-Token interceptor and useexcludePathPatternsMethod applies the exclusion path defined in the configuration file to the interceptor.

Detailed explanation

Depend on configuration

Sa-Token is a lightweight permission authentication framework that can help us easily manage user login status and permission authentication. By introducingsa-token-spring-boot-starterDependency, we can easily integrate it into our Spring Boot project.

Configuration classSecurityProperties

SecurityPropertiesThe function of the class is to read and store the exclude path defined in the configuration file toexcludesin the array. By using@ConfigurationPropertiesAnnotation, we can prefix it assecurityThe attributes of this class are bound toexcludeson the field. The advantage of this is that the exclusion path can be dynamically configured through configuration files for easy management and maintenance.

Configuration File

In the configuration file, we define the paths that need to be excluded. These paths will not be intercepted by the interceptor and can be accessed directly. The configuration file supports YAML format and Properties format, and select the appropriate format for configuration according to the project needs.

Interceptor configuration

existWebConfigIn the class, we implementedWebMvcConfigurerInterface and rewrittenaddInterceptorsmethod. In this method, we create a Sa-Token interceptor and pass("/**")Match all paths. For matching paths, we use()Method to check the login status. If the user is not logged in, it will be intercepted and the corresponding unlogged in prompt will be returned.

passexcludePathPatternsMethod, we willSecurityPropertiesThe exclude paths obtained in the interceptor are applied. In this way, the exclusion path defined in the configuration file will not be intercepted by the interceptor and can be accessed directly.

Summarize

Through this article, we understand how to use Sa-Token in Spring Boot to implement path interception and specific interface release. We first introduced the dependency of Sa-Token and then defined a configuration classSecurityProperties, used to read and store exclusion path information. Next, define the path to exclude in the configuration file andWebConfigThe Sa-Token interceptor is configured in the class and the exclusion path is applied to the interceptor. Finally, through testing and verification, ensure that the configuration takes effect, allowing the release of specific paths and permission verification of other paths is achieved.

This method can help developers more flexibly manage access control in web applications and improve system security and maintainability. If you have more customization needs, you can further configure and expand according to the Sa-Token documentation.

The above is the detailed content of SpringBoot using Sa-Token to implement path interception and specific interface release. For more information about SpringBoot Sa-Token interception and release, please pay attention to my other related articles!