sa-token-advanced

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Sa-Token 高级安全特性

Sa-Token Advanced Security Features

基于
sa-token-doc/up/
深入 +
fun/
高级 +
arch/
架构文档。
Built on in-depth coverage of
sa-token-doc/up/
, advanced material in
fun/
, and architectural documentation in
arch/
.

适用场景

Applicable Scenarios

当用户需要以下场景时,激活此技能:
  • 敏感操作二次验证 — 删除仓库/修改密码等操作需要再次确认身份
  • 账号违规处罚 — 按服务维度封禁(只禁言不禁购)、按违规等级处罚
  • 后台模拟用户 — 客服人员需要临时以用户身份操作
  • 多套账号体系 — 系统中同时存在User和Admin两套独立的账号表
  • 全局事件记录 — 记录所有用户的登录/注销/踢人/封禁等操作日志
  • 密码加密存储 — 用户密码的安全存储与验证
Activate this skill when the user needs any of the following:
  • Secondary verification for sensitive operations — actions such as deleting a repository or changing a password require identity confirmation again
  • Account violation penalties — ban accounts by service dimension (restrict commenting but not purchasing) or apply penalties based on violation severity
  • Admin user impersonation — customer service personnel need to temporarily perform operations as a user
  • Multiple account systems — the system contains separate account tables for User and Admin
  • Global event logging — record operation logs for all user login, logout, kick, ban, and similar events
  • Encrypted password storage — securely store and verify user passwords

Workflow

Workflow

Step 1. 确定需求 — 选择二级认证/封禁/多账号/侦听器等具体功能 Step 2. 编写代码 — 根据API文档实现对应功能 Step 3. 配置注册 — 注册侦听器、配置过滤器、定义多账号体系 Step 4. 测试验证 — 验证功能行为符合预期
Step 1. Identify Requirements — select the required feature, such as secondary authentication, account banning, multi-account authentication, or listeners Step 2. Write the Code — implement the selected feature according to the API documentation Step 3. Configure and Register — register listeners, configure filters, and define multiple account systems Step 4. Test and Validate — verify that the behavior meets the expected requirements

Capability Boundaries

Capability Boundaries

✅ Strong Suits

✅ Key Strengths

  1. 二级认证 —
    openSafe()
    /
    checkSafe()
    /@
    SaCheckSafe
    敏感操作二次验证
  2. 账号封禁 — 全封禁/分类封禁(comment/order/shop)/阶梯封禁(level)
  3. 身份切换 —
    switchTo()
    /
    endSwitch()
    模拟其他账号
  4. 多账号认证 — StpUserUtil模式 + StpKit门面模式,多套账号体系
  5. 全局侦听器 — SaTokenListener接口(登录/注销/踢人/封禁等10+事件)
  6. 全局过滤器 — SaServletFilter + SaReactorFilter,统一安全头设置
  7. 密码加密 — 5种算法:MD5/SHA/AES/RSA/BCrypt + TOTP验证码
  8. 会话查询 — SaTerminalInfo终端列表 + searchTokenValue/TokenSession/Session
  9. Http Basic/Digest — @SaCheckHttpBasic / @SaCheckHttpDigest
  10. 防火墙 — IP黑白名单 + 请求频率限制
  11. 自定义注解 — 组合注解/自定义鉴权注解
  1. Secondary authentication —
    openSafe()
    /
    checkSafe()
    /@
    SaCheckSafe
    for secondary verification of sensitive operations
  2. Account banning — full bans/category-specific bans(comment/order/shop)/tiered bans(level)
  3. Identity switching —
    switchTo()
    /
    endSwitch()
    for impersonating another account
  4. Multi-account authentication — StpUserUtil pattern + StpKit facade pattern for multiple account systems
  5. Global listeners — SaTokenListener interface for 10+ events, including login, logout, kick, and ban
  6. Global filters — SaServletFilter + SaReactorFilter for unified security header configuration
  7. Password encryption — 5 algorithms: MD5/SHA/AES/RSA/BCrypt + TOTP verification codes
  8. Session queries — SaTerminalInfo terminal lists + searchTokenValue/TokenSession/Session
  9. HTTP Basic/Digest — @SaCheckHttpBasic / @SaCheckHttpDigest
  10. Firewall — IP allowlists and blocklists + request rate limiting
  11. Custom annotations — composite annotations/custom authorization annotations

⚠️ Requirements

⚠️ Requirements

  1. 所有功能都基于
    sa-token-core
    ,部分功能需要登录后才能使用
  2. 全局侦听器需要注册到Spring容器(@Component或手动注册)
  3. 多账号认证需要自行定义账号体系名称
  1. All features are based on
    sa-token-core
    , and some features require the user to be logged in first
  2. Global listeners must be registered in the Spring container (@Component or manual registration)
  3. Multi-account authentication requires you to define your own account system names

❌ Out of Scope

❌ Out of Scope

  1. 基础登录/权限/注解鉴权 → sa-token
  2. SSO单点登录 → sa-token-sso
  3. OAuth2.0 服务端 → sa-token-oauth2
  4. 微服务鉴权 → sa-token-micro
  1. Basic login/permissions/annotation authorization → sa-token
  2. SSO single sign-on → sa-token-sso
  3. OAuth 2.0 server → sa-token-oauth2
  4. Microservice authentication and authorization → sa-token-micro

参考文档

Reference Documentation

主题文件来源
二级认证(safe-auth)references/safe-auth.mdGitHub
账号封禁(分类+阶梯)references/disable.mdGitHub
身份切换(mock-person)references/mock-person.mdGitHub
多账号认证references/many-account.mdGitHub
密码加密+HttpBasicreferences/password-basic.mdGitHub
全局侦听器+全局过滤器references/listener-filter.mdGitHub
TopicFileSource
Secondary authentication (safe-auth)references/safe-auth.mdGitHub
Account banning (category-specific + tiered)references/disable.mdGitHub
Identity switching (mock-person)references/mock-person.mdGitHub
Multi-account authenticationreferences/many-account.mdGitHub
Password encryption + HTTP Basicreferences/password-basic.mdGitHub
Global listeners + global filtersreferences/listener-filter.mdGitHub

核心 API 速查

Core API Quick Reference

java
// === 二级认证 ===
StpUtil.openSafe("update-password");         // 开启(默认120秒)
StpUtil.checkSafe("update-password");         // 校验
@SaCheckSafe("update-password")               // 注解

// === 账号封禁 ===
StpUtil.disable(10001, "comment", 200);       // 分类封禁
StpUtil.disableLevel(10001, "comment", 2, 200); // 阶梯封禁
StpUtil.untieDisable(10001, "comment");       // 解封
@SaCheckDisable("comment")                     // 注解

// === 身份切换 ===
StpUtil.switchTo(10001);                       // 切换到其他账号
StpUtil.switchTo(10001, () -> { ... });        // Lambda作用域切换

// === 多账号 ===
StpUserUtil.login(10001);                     // User体系
StpKit.admin.login(10001);                    // StpKit门面

// === 密码加密 ===
SaSecureUtil.md5("123456");
SaSecureUtil.aesEncrypt(key, "data");
SaSecureUtil.rsaEncryptByPublic(publicKey, text);
SaTotpUtil.generateCode("secret");
SaSecureUtil.bCryptPasswordEncoder("123456");

// === 全局侦听器 ===
SaTokenEventCenter.registerListener(listener);
@Component class MyListener extends SaTokenListenerForSimple { ... }

// === 会话查询 ===
StpUtil.searchTokenValue(keyword, start, size, sort);
StpUtil.searchSessionId(keyword, start, size, sort);
java
// === 二级认证 ===
StpUtil.openSafe("update-password");         // 开启(默认120秒)
StpUtil.checkSafe("update-password");         // 校验
@SaCheckSafe("update-password")               // 注解

// === 账号封禁 ===
StpUtil.disable(10001, "comment", 200);       // 分类封禁
StpUtil.disableLevel(10001, "comment", 2, 200); // 阶梯封禁
StpUtil.untieDisable(10001, "comment");       // 解封
@SaCheckDisable("comment")                     // 注解

// === 身份切换 ===
StpUtil.switchTo(10001);                       // 切换到其他账号
StpUtil.switchTo(10001, () -> { ... });        // Lambda作用域切换

// === 多账号 ===
StpUserUtil.login(10001);                     // User体系
StpKit.admin.login(10001);                    // StpKit门面

// === 密码加密 ===
SaSecureUtil.md5("123456");
SaSecureUtil.aesEncrypt(key, "data");
SaSecureUtil.rsaEncryptByPublic(publicKey, text);
SaTotpUtil.generateCode("secret");
SaSecureUtil.bCryptPasswordEncoder("123456");

// === 全局侦听器 ===
SaTokenEventCenter.registerListener(listener);
@Component class MyListener extends SaTokenListenerForSimple { ... }

// === 会话查询 ===
StpUtil.searchTokenValue(keyword, start, size, sort);
StpUtil.searchSessionId(keyword, start, size, sort);

FAQ

FAQ

Q: 二级认证和普通登录有什么区别? A: 普通登录是第一次身份验证。二级认证是在已经登录的基础上,对敏感操作进行第二次验证(如修改密码、删除仓库)。两者独立。
Q: 账号封禁的三种级别怎么用? A: 简单违规用全封禁。按服务维度违规用分类封禁(如只禁言不禁购)。需要梯度处罚用阶梯封禁(如首次违规level1,多次违规level3)。
Q: StpUserUtil和StpKit有什么区别? A: StpUserUtil是内置的User账号体系。StpKit门面模式可以自定义任意多的账号体系(如User、Admin、Teacher),更加灵活。
Q: 全局侦听器能监听到哪些事件? A: 登录、注销、踢下线、顶下线、封禁、解封、二级认证开启/关闭、Session创建/销毁、Token续期,共11种事件。
Q: SaServletFilter和SaInterceptor怎么选? A: 需要过滤静态资源或设置安全响应头选SaServletFilter。只需要Controller层鉴权选SaInterceptor。两者可以同时使用。
Q: 如何自定义鉴权注解? A: 实现
SaAnnotationStrategy
的自定义注解处理器,可以参考官方demo中的
custom_annotation
包。
Q: What is the difference between secondary authentication and normal login? A: Normal login is the first identity verification. Secondary authentication performs a second verification on top of an existing login for sensitive operations, such as changing a password or deleting a repository. The two are independent.
Q: How should the three levels of account banning be used? A: Use a full ban for simple violations. Use category-specific bans for violations tied to a service dimension, such as restricting commenting but not purchasing. Use tiered bans for graduated penalties, such as level 1 for a first violation and level 3 for repeated violations.
Q: What is the difference between StpUserUtil and StpKit? A: StpUserUtil is the built-in User account system. The StpKit facade pattern allows you to define any number of custom account systems, such as User, Admin, and Teacher, providing greater flexibility.
Q: Which events can the global listener monitor? A: Login, logout, forced kick, session displacement, ban, unban, secondary authentication start/end, Session creation/destruction, and Token renewal—11 event types in total.
Q: How do I choose between SaServletFilter and SaInterceptor? A: Choose SaServletFilter when you need to filter static resources or configure security response headers. Choose SaInterceptor when you only need Controller-layer authorization. Both can be used together.
Q: How do I create a custom authorization annotation? A: Implement a custom annotation processor through
SaAnnotationStrategy
. You can refer to the
custom_annotation
package in the official demo.

Gotchas

Gotchas

  1. StpInterface可实现
    isDisabled()
    自定义封禁逻辑
    — 默认封禁在内存中,重启丢失
  2. 多账号体系可在注解中通过
    type
    属性指定
    — 如
    @SaCheckLogin(type = "user")
  3. 全局侦听器建议使用
    SaTokenListenerForSimple
    简化实现
    — 只重写需要的方法
  4. 二级认证默认有效期120秒 — 可根据业务调整
  5. 阶梯封禁的level值越大代表封禁越严重 —
    checkDisableLevel(3)
    表示level≥3才阻止
  6. switchTo的Lambda方式比手动endSwitch更安全 — 不会忘记恢复身份
  7. 全局过滤器设置安全响应头时要注意浏览器兼容性
  8. Http Basic认证的账号密码在网络传输中是明文 — 需配合HTTPS使用
  1. StpInterface
    can implement custom ban logic through
    isDisabled()
    — default bans are stored in memory and are lost after a restart
  2. Multi-account systems can specify the account system through the
    type
    attribute in annotations — for example,
    @SaCheckLogin(type = "user")
  3. Using
    SaTokenListenerForSimple
    is recommended for global listeners — override only the methods you need
  4. Secondary authentication has a default validity period of 120 seconds — adjust it according to your business requirements
  5. A higher tiered-ban level means a more severe ban —
    checkDisableLevel(3)
    blocks access only when level≥3
  6. The Lambda form of switchTo is safer than manually calling endSwitch — it prevents you from forgetting to restore the original identity
  7. When configuring security response headers through a global filter, account for browser compatibility
  8. HTTP Basic credentials are transmitted in plaintext over the network — use it together with HTTPS

Data Privacy

Data Privacy

本技能不收集、存储或传输任何用户数据。所有代码示例仅供本地开发参考。
This skill does not collect, store, or transmit any user data. All code examples are provided for local development reference only.