Simple and easy to learn SA token fast building -- authority authentication "I"

Environment construction

SA token official website document
Redis installation is very simple. There are instances written into the configuration file, and the token is saved in redis

AOP relies on annotation implementation, the last one
Implementation: annotation authentication can be used in specific methods, not just on the controller

        <!--mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
        <!-- Sa-Token Authority authentication, Online documentation: http://sa-token.dev33.cn/ -->
        <dependency>
            <groupId>cn.dev33</groupId>
            <artifactId>sa-token-spring-boot-starter</artifactId>
            <version>1.28.0</version>
        </dependency>
        <!-- redis Dependent package -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <!--Sa-Token-Redis The version of the integration package should be the same as possible Sa-Token-Starter The version of integration package is consistent-->
        <!-- Sa-Token integration Redis (use jackson Serialization mode) -->
        <dependency>
            <groupId>cn.dev33</groupId>
            <artifactId>sa-token-dao-redis-jackson</artifactId>
            <version>1.28.0</version>
        </dependency>
        <!-- provide Redis Connection pool -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>
        
        <!-- Sa-Token integration SpringAOP Implement annotation authentication -->
        <dependency>
            <groupId>cn.dev33</groupId>
            <artifactId>sa-token-spring-aop</artifactId>
            <version>1.28.0</version>
        </dependency>

application-dev.yml

server:
  port: 30991
  servlet:
    context-path: /jay-admin

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/kuMing?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: 123456789
  redis:
    # Redis server address
    host: 127.0.0.1
    port: 6379
    # Redis database index (0 by default)
    database: 1
    timeout: 5000
#    Thread safety
    lettuce:
      pool:
        # Maximum connections in connection pool
        max-active: 200
        # Maximum blocking waiting time of connection pool (negative value indicates no limit)
        max-wait: -1ms
        # Maximum free connections in connection pool
        max-idle: 10
        # Minimum free connections in connection pool
        min-idle: 0
  jta:
    atomikos:
      datasource:
        xa-data-source-class-name:
#    There are two redis modes. The following threads are unsafe
#    jedis:
#      pool:
#        max-active: 50
#        max-wait: 3000
#        max-idle: 20
#        min-idle: 2
mybatis-plus:
  mapper-locations: classpath:/mapper/*.xml
# SA token configuration
sa-token:
  # token name (also cookie name)
  token-name: satoken
  # The valid period of the token is 30 days by default, and - 1 means it will never expire
  timeout: 2592000
  # Temporary validity period of token (token will be deemed expired if there is no operation within the specified time) unit: seconds
  activity-timeout: -1
  # Whether to allow concurrent login of the same account (when it is true, it is allowed to log in together; when it is false, the new login will crowd out the old login)
  is-concurrent: true
  # Whether to share a token when multiple people log in to the same account (if true, all logins share a token; if false, create a new token for each login)
  is-share: false
  # token style
  token-style: random-128
  # Output operation log
  is-log: false
  sso:
    auth-url: http://sa-sso-server.com:9000/sso/auth

Startup class: system out. Println ("start successfully: SA token configuration is as follows:" + SaManager.getConfig());

Global interception rules

Route interception rules

/**
 * @author Jay
 * @version V1.0
 * @Package com.shanghai.test1114.config
 * @date 2022/1/27 3:55 afternoon
 * Interceptor
 * In the higher version of SpringBoot (≥ 2.6.x), the @ EnableWebMvc annotation needs to be added to make the registered interceptor effective.
 * Interceptor mode and AOP mode cannot be integrated at the same time
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    // Register the annotation interceptor of SA token and turn on the annotation authentication function
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // Register the annotation interceptor and exclude the interface address that does not require annotation authentication (independent of the login interceptor)
        //registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");

        // Register the route interceptor of SA token
        //The following is that you can access other interfaces only after logging in. swagger releases the accessible route interception rules
        registry.addInterceptor(new SaRouteInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/user/doLogin","/swagger-ui.html/**","/swagger-resources/**")
        ;
    }

Function realization

@GetMapping("/doLogin")
StpUtil.login(user.getUsername()); Sign in
StpUtil.logout(); cancellation
StpUtil.kickout(RoolId); Kick the line

// Mark the account id of the current session login 
// Suggested parameter type: long | int | String. Complex types such as User and Admin cannot be passed in
StpUtil.login(Object id);     

// Current session logout login
StpUtil.logout();

// Gets whether the current session has been logged in, and returns true = logged in, false = not logged in
StpUtil.isLogin();

// Check whether the current session has been logged in. If not, an exception will be thrown: ` NotLoginException`
StpUtil.checkLogin()

methodReturn valueinterpretation
Sign in:StpUtil.login(πŸ†”)voidMark login account
StpUtil.login(πŸ†”οΌŒtrue)voidRemember my function (write a permanent Cookie in the browser to store the Token. At this time, the Token is still valid even if the user restarts the browser)
StpUtil.login(πŸ†”οΌŒfalse)voidDo not remember my function (write a temporary Cookie to store the Token in the browser, and the Token will disappear after the user restarts the browser, resulting in session failure)
StpUtil.login(10001, new SaLoginModel().setDevice("PC").setIsLastingCookie(true).setTimeout(60 * 60 * 24 * 7) )voidThe client device ID of this login is used to specify the device name of this login when [same end mutually exclusive login]; Whether it is a persistent Cookie (the temporary Cookie will be automatically deleted when the browser is closed, and the persistent Cookie will still exist after reopening); Specify the validity period of this login token, unit: seconds (if not specified, the timeout value of global configuration will be taken automatically)
cancellation:StpUtil.logout()voidForce logoff of current session
StpUtil.logout(πŸ†”)voidForce specified account cancellation
StpUtil.logout(πŸ†”, "PC")voidForce the designated account to log off at the designated end
StpUtil.logoutByTokenValue("token")voidForce specified Token to logoff
Kick line:StpUtil.kickout(user.getUsername())voidKick people off the line
StpUtil.kickout(10001, "PC")voidKick off the line at the specified end of the specified account
StpUtil.kickoutByTokenValue("token")voidSpecify Token kick off line
Ban:StpUtil.disable(πŸ†”, 86400)voidAccount number and blocking time s, - 1 permanent
StpUtil.isDisable(πŸ†”)booleanWhether the account has been blocked {true = blocked, false = not blocked}
StpUtil.getDisableTime(πŸ†”)longAccount remaining blocking time s
StpUtil.untieDisable(πŸ†”)voidAccount unsealing

The difference between forced logoff and kicking off:

Forced logoff is equivalent to the other party actively calling the logoff method. If you visit again, you will be prompted that the Token is invalid
Kicking a person off the line will not clear the Token information, but mark it with a specific mark. If you visit again, you will be prompted that the Token has been kicked off the line

Account being logged in is blocked:

The ban will not drop the line
Kick it first to drop the line and ban it
StpUtil.kickout(πŸ†”);
StpUtil.disable(πŸ†”, 86400);

Annotation authentication

The AOP package is imported in front to realize method authentication

    @GetMapping("/doSelect/account")
    @ApiOperation("All users")
//    @SaCheckLogin / / login authentication: this method can be accessed only after login
//    @SaCheckRole("admin") / / role authentication: you must have a specified role to enter this method
//    @Sacheckpermission ("user get") / / permission authentication: you must have the specified permission to enter this method
//    @Whether sacheckpermission (value = {"user add", "user all", "user delete"}, mode = Samode. Or) requires only one permission release
//    @Sacheckpermission (value = "user add", orrole = "admin") has permissions and roles
//                                           orRole = {"admin", "manager", "staff"} there is only one role
//                                           orRole = {"admin, manager, staff"} means that you must have three roles at the same time
//    @SaCheckSafe() / / level 2 authentication: this method can only be accessed after level 2 authentication
//    @Sacheckbasic (account = "Sa: 123456") / / HTTP Basic authentication: you can enter this method only after passing Basic authentication
    public ResponseWeb<List<UserResp>> doSelectAccount() {
        List<User> user = userService.doSelectAccount();
        List<UserResp> respList = userDtoToMapper.userToUserResp(user);
        return ResponseUtils.success(respList);
    }

Interception rules (advanced version)

@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // Register route interceptor and customize authentication rules 
        registry.addInterceptor(new SaRouteInterceptor((req, res, handler)->{
            // Divide the modules according to the route, and different modules have different authentication 
            SaRouter.match("/user/**", r -> StpUtil.checkPermission("user"));
            SaRouter.match("/admin/**", r -> StpUtil.checkPermission("admin"));
            SaRouter.match("/goods/**", r -> StpUtil.checkPermission("goods"));
            SaRouter.match("/orders/**", r -> StpUtil.checkPermission("orders"));
            SaRouter.match("/notice/**", r -> StpUtil.checkPermission("notice"));
            SaRouter.match("/comment/**", r -> StpUtil.checkPermission("comment"));
        })).addPathPatterns("/**");
    }
}

SA token official website document

Keywords: Java Redis Spring Boot

Added by sholtzrevtek on Fri, 28 Jan 2022 12:28:40 +0200