Table of Contents
1. Design Ideas
2. Login and logout
TokenInfo is the Token information Model, used to describe the common parameters of a Token:
5. Let’s do a small test to deepen our understanding
Home Java javaTutorial How SpringBoot uses Sa-Token to implement login authentication

How SpringBoot uses Sa-Token to implement login authentication

May 27, 2023 pm 08:34 PM
springboot sa-token

1. Design Ideas

For some interfaces that can only be accessed after logging in (for example: querying my account information), our usual approach is to add a layer of interface verification:

  • If the verification passes, then: return data normally.

  • If the verification fails, then: throw an exception and inform it that it needs to log in first.

So, what is the basis for determining whether a session is logged in? Let’s first briefly analyze the login access process:

  • The user submits the name password parameter and calls the login interface.

  • If the login is successful, the user's Token session credentials will be returned.

  • Each subsequent request by the user will carry this Token.

  • The server determines whether the login for this session is successful based on the Token.

The so-called login authentication refers to the process in which the server verifies the account password and issues a Token session credential to the user. This Token is also the key to our subsequent judgment of whether the session is logged in.

Dynamic diagram demonstration:

How SpringBoot uses Sa-Token to implement login authentication

Next, we will introduce how to use Sa-Token to complete the login authentication operation in SpringBoot.

Sa-Token is a java permission authentication framework that mainly solves a series of permission-related issues such as login authentication, permission authentication, single sign-on, OAuth3, microservice gateway authentication, etc.
Gitee open source address: https://gitee.com/dromara/sa-token

First introduce Sa-Token dependency into the project:

<!-- Sa-Token 权限认证 -->
<dependency>
    <groupId>cn.dev33</groupId>
    <artifactId>sa-token-spring-boot-starter</artifactId>
    <version>1.34.0</version>
</dependency>
Copy after login

Note: If you are using For SpringBoot 3.x, you only need to modify sa-token-spring-boot-starter to sa-token-spring-boot3-starter.

2. Login and logout

Based on the above ideas, we need a function for session login:

// 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等等
StpUtil.login(Object id);
Copy after login

With just this sentence of code, the session login can be successful. In fact, , Sa-Token has done a lot of work behind the scenes, including but not limited to:

  • Check whether this account has been logged in before

  • is The account generates Token credentials and Session

  • Notify the global listener that the xx account has successfully logged in

  • Inject the Token into the request context

  • Wait for other work... Token creates a Token credential for this account and returns it to the front end through the Cookie context.

  • So under normal circumstances, our login interface code will be roughly similar to the following:
// 会话登录接口 
@RequestMapping("doLogin")
public SaResult doLogin(String name, String pwd) {
    // 第一步:比对前端提交的账号名称、密码
    if("zhang".equals(name) && "123456".equals(pwd)) {
        // 第二步:根据账号id,进行登录 
        StpUtil.login(10001);
        return SaResult.ok("登录成功");
    }
    return SaResult.error("登录失败");
}
Copy after login

If you have no pressure to read the above code, you may notice a slightly strange point: This The office only performed session login, but did not actively return Token information to the front end.

Is it because it is not needed? Strictly speaking, it is required, but the StpUtil.login(id) method takes advantage of the automatic injection feature of Cookie, omitting your handwritten code to return the Token.

If you don’t know much about the Cookie function, don’t worry, we will explain the Cookie function in detail in the [Backend and Backend Separation] chapter later. Now you only need to understand the two most basic points:


Cookie can write the Token value to the browser from the back-end control.

  • Cookie will automatically submit the Token value every time the front end initiates a request.

  • Therefore, with the support of the Cookie function, we can complete login authentication with just one line of code StpUtil.login(id).

  • In addition to the login method, we also need:
// 当前会话注销登录
StpUtil.logout();

// 获取当前会话是否已经登录,返回true=已登录,false=未登录
StpUtil.isLogin();

// 检验当前会话是否已经登录, 如果未登录,则抛出异常:`NotLoginException`
StpUtil.checkLogin();
Copy after login

Exception NotLoginException means that the current session has not been logged in. There are many possible reasons:

The front-end did not submit the Token, and the Token submitted by the front-end is invalid. , the Token submitted by the front end has expired...and so on.

Sa-Token non-login scenario value reference table:


Scenario valueCorresponding constant-1NotLoginException.NOT_TOKENNotLoginException.INVALID_TOKENNotLoginException.TOKEN_TIMEOUTNotLoginException.BE_REPLACEDNotLoginException.KICK_OUT#So, how to get the scene value? Stop talking nonsense and go straight to the code:
// 全局异常拦截(拦截项目中的NotLoginException异常)
@ExceptionHandler(NotLoginException.class)
public SaResult handlerNotLoginException(NotLoginException nle)
        throws Exception {

    // 打印堆栈,以供调试
    nle.printStackTrace(); 
    
    // 判断场景值,定制化异常信息 
    String message = "";
    if(nle.getType().equals(NotLoginException.NOT_TOKEN)) {
        message = "未提供token";
    }
    else if(nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
        message = "token无效";
    }
    else if(nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
        message = "token已过期";
    }
    else if(nle.getType().equals(NotLoginException.BE_REPLACED)) {
        message = "token已被顶下线";
    }
    else if(nle.getType().equals(NotLoginException.KICK_OUT)) {
        message = "token已被踢下线";
    }
    else {
        message = "当前会话未登录";
    }
    
    // 返回给前端
    return SaResult.error(message);
}
Copy after login
Note: The above code is not the best way to process logic. It is just to demonstrate the acquisition and application of scene values ​​​​with the simplest code. You can customize it according to your own project needs. Customized processing
Meaning description
Failed to read Token from the request-2
The Token has been read, but the Token is invalid-3
The Token has been read, but the Token has expired-4
has Token has been read, but the Token has been taken offline-5
Token has been read, but the Token has been Kicked offline

3. Session query

// 获取当前会话账号id, 如果未登录,则抛出异常:`NotLoginException`
StpUtil.getLoginId();

// 类似查询API还有:
StpUtil.getLoginIdAsString();    // 获取当前会话账号id, 并转化为`String`类型
StpUtil.getLoginIdAsInt();       // 获取当前会话账号id, 并转化为`int`类型
StpUtil.getLoginIdAsLong();      // 获取当前会话账号id, 并转化为`long`类型

// ---------- 指定未登录情形下返回的默认值 ----------

// 获取当前会话账号id, 如果未登录,则返回null 
StpUtil.getLoginIdDefaultNull();

// 获取当前会话账号id, 如果未登录,则返回默认值 (`defaultValue`可以为任意类型)
StpUtil.getLoginId(T defaultValue);
Copy after login

4. Token query

// 获取当前会话的token值
StpUtil.getTokenValue();

// 获取当前`StpLogic`的token名称
StpUtil.getTokenName();

// 获取指定token对应的账号id,如果未登录,则返回 null
StpUtil.getLoginIdByToken(String tokenValue);

// 获取当前会话剩余有效期(单位:s,返回-1代表永久有效)
StpUtil.getTokenTimeout();

// 获取当前会话的token信息参数
StpUtil.getTokenInfo();
Copy after login

TokenInfo is the Token information Model, used to describe the common parameters of a Token:

{
    "tokenName": "satoken",           // token名称
    "tokenValue": "e67b99f1-3d7a-4a8d-bb2f-e888a0805633",      // token值
    "isLogin": true,                  // 此token是否已经登录
    "loginId": "10001",               // 此token对应的LoginId,未登录时为null
    "loginType": "login",              // 账号类型标识
    "tokenTimeout": 2591977,          // token剩余有效期 (单位: 秒)
    "sessionTimeout": 2591977,        // User-Session剩余有效时间 (单位: 秒)
    "tokenSessionTimeout": -2,        // Token-Session剩余有效时间 (单位: 秒) (-2表示系统中不存在这个缓存)
    "tokenActivityTimeout": -1,       // token剩余无操作有效时间 (单位: 秒)
    "loginDevice": "default-device"   // 登录设备类型 
}
Copy after login

5. Let’s do a small test to deepen our understanding

Create a new LoginAuthController and copy the following code

package com.pj.cases.use;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;

/**
 * Sa-Token 登录认证示例 
 * 
 * @author kong
 * @since 2022-10-13
 */
@RestController
@RequestMapping("/acc/")
public class LoginAuthController {

    // 会话登录接口  ---- http://localhost:8081/acc/doLogin?name=zhang&pwd=123456
    @RequestMapping("doLogin")
    public SaResult doLogin(String name, String pwd) {
        
        // 第一步:比对前端提交的 账号名称 & 密码 是否正确,比对成功后开始登录 
        //         此处仅作模拟示例,真实项目需要从数据库中查询数据进行比对 
        if("zhang".equals(name) && "123456".equals(pwd)) {
            
            // 第二步:根据账号id,进行登录 
            //         此处填入的参数应该保持用户表唯一,比如用户id,不可以直接填入整个 User 对象 
            StpUtil.login(10001);
            
            // SaResult 是 Sa-Token 中对返回结果的简单封装,下面的示例将不再赘述 
            return SaResult.ok("登录成功");
        }
        
        return SaResult.error("登录失败");
    }

    // 查询当前登录状态  ---- http://localhost:8081/acc/isLogin
    @RequestMapping("isLogin")
    public SaResult isLogin() {
        // StpUtil.isLogin() 查询当前客户端是否登录,返回 true 或 false 
        boolean isLogin = StpUtil.isLogin();
        return SaResult.ok("当前客户端是否登录:" + isLogin);
    }

    // 校验当前登录状态  ---- http://localhost:8081/acc/checkLogin
    @RequestMapping("checkLogin")
    public SaResult checkLogin() {
        // 检验当前会话是否已经登录, 如果未登录,则抛出异常:`NotLoginException`
        StpUtil.checkLogin();

        // 抛出异常后,代码将走入全局异常处理(GlobalException.java),如果没有抛出异常,则代表通过了登录校验,返回下面信息 
        return SaResult.ok("校验登录成功,这行字符串是只有登录后才会返回的信息");
    }

    // 获取当前登录的账号是谁  ---- http://localhost:8081/acc/getLoginId
    @RequestMapping("getLoginId")
    public SaResult getLoginId() {
        // 需要注意的是,StpUtil.getLoginId() 自带登录校验效果
        // 也就是说如果在未登录的情况下调用这句代码,框架就会抛出 `NotLoginException` 异常,效果和 StpUtil.checkLogin() 是一样的 
        Object userId = StpUtil.getLoginId();
        System.out.println("当前登录的账号id是:" + userId);
        
        // 如果不希望 StpUtil.getLoginId() 触发登录校验效果,可以填入一个默认值
        // 如果会话未登录,则返回这个默认值,如果会话已登录,将正常返回登录的账号id 
        Object userId2 = StpUtil.getLoginId(0);
        System.out.println("当前登录的账号id是:" + userId2);
        
        // 或者使其在未登录的时候返回 null 
        Object userId3 = StpUtil.getLoginIdDefaultNull();
        System.out.println("当前登录的账号id是:" + userId3);
        
        // 类型转换:
        // StpUtil.getLoginId() 返回的是 Object 类型,你可以使用以下方法指定其返回的类型 
        int userId4 = StpUtil.getLoginIdAsInt();  // 将返回值转换为 int 类型 
        long userId5 = StpUtil.getLoginIdAsLong();  // 将返回值转换为 long 类型 
        String userId6 = StpUtil.getLoginIdAsString();  // 将返回值转换为 String 类型 
        
        // 疑问:数据基本类型不是有八个吗,为什么只封装以上三种类型的转换?
        // 因为大多数项目都是拿 int、long 或 String 声明 UserId 的类型的,实在没见过哪个项目用 double、float、boolean 之类来声明 UserId 
        System.out.println("当前登录的账号id是:" + userId4 + " --- " + userId5 + " --- " + userId6);
        
        // 返回给前端 
        return SaResult.ok("当前客户端登录的账号id是:" + userId);
    }

    // 查询 Token 信息  ---- http://localhost:8081/acc/tokenInfo
    @RequestMapping("tokenInfo")
    public SaResult tokenInfo() {
        // TokenName 是 Token 名称的意思,此值也决定了前端提交 Token 时应该使用的参数名称 
        String tokenName = StpUtil.getTokenName();
        System.out.println("前端提交 Token 时应该使用的参数名称:" + tokenName);
        
        // 使用 StpUtil.getTokenValue() 获取前端提交的 Token 值 
        // 框架默认前端可以从以下三个途径中提交 Token:
        //         Cookie         (浏览器自动提交)
        //         Header头    (代码手动提交)
        //         Query 参数    (代码手动提交) 例如: /user/getInfo?satoken=xxxx-xxxx-xxxx-xxxx 
        // 读取顺序为: Query 参数 --> Header头 -- > Cookie 
        // 以上三个地方都读取不到 Token 信息的话,则视为前端没有提交 Token 
        String tokenValue = StpUtil.getTokenValue();
        System.out.println("前端提交的Token值为:" + tokenValue);
        
        // TokenInfo 包含了此 Token 的大多数信息 
        SaTokenInfo info = StpUtil.getTokenInfo();
        System.out.println("Token 名称:" + info.getTokenName());
        System.out.println("Token 值:" + info.getTokenValue());
        System.out.println("当前是否登录:" + info.getIsLogin());
        System.out.println("当前登录的账号id:" + info.getLoginId());
        System.out.println("当前登录账号的类型:" + info.getLoginType());
        System.out.println("当前登录客户端的设备类型:" + info.getLoginDevice());
        System.out.println("当前 Token 的剩余有效期:" + info.getTokenTimeout()); // 单位:秒,-1代表永久有效,-2代表值不存在
        System.out.println("当前 Token 的剩余临时有效期:" + info.getTokenActivityTimeout()); // 单位:秒,-1代表永久有效,-2代表值不存在
        System.out.println("当前 User-Session 的剩余有效期" + info.getSessionTimeout()); // 单位:秒,-1代表永久有效,-2代表值不存在
        System.out.println("当前 Token-Session 的剩余有效期" + info.getTokenSessionTimeout()); // 单位:秒,-1代表永久有效,-2代表值不存在
        
        // 返回给前端 
        return SaResult.data(StpUtil.getTokenInfo());
    }
    
    // 会话注销  ---- http://localhost:8081/acc/logout
    @RequestMapping("logout")
    public SaResult logout() {
        // 退出登录会清除三个地方的数据:
        //         1、Redis中保存的 Token 信息
        //         2、当前请求上下文中保存的 Token 信息 
        //         3、Cookie 中保存的 Token 信息(如果未使用Cookie模式则不会清除)
        StpUtil.logout();
        
        // StpUtil.logout() 在未登录时也是可以调用成功的,
        // 也就是说,无论客户端有没有登录,执行完 StpUtil.logout() 后,都会处于未登录状态 
        System.out.println("当前是否处于登录状态:" + StpUtil.isLogin());
        
        // 返回给前端 
        return SaResult.ok("退出登录成功");
    }
    
}
Copy after login

The above is the detailed content of How SpringBoot uses Sa-Token to implement login authentication. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

How to get the value in application.yml in springboot How to get the value in application.yml in springboot Jun 03, 2023 pm 06:43 PM

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic

See all articles