Sa-Token Advanced Security Features
Built on in-depth coverage of
, advanced material in
, and architectural documentation in
.
Applicable Scenarios
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
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
✅ Key Strengths
- Secondary authentication — //@ for secondary verification of sensitive operations
- Account banning — full bans/category-specific bans(comment/order/shop)/tiered bans(level)
- Identity switching — / for impersonating another account
- Multi-account authentication — StpUserUtil pattern + StpKit facade pattern for multiple account systems
- Global listeners — SaTokenListener interface for 10+ events, including login, logout, kick, and ban
- Global filters — SaServletFilter + SaReactorFilter for unified security header configuration
- Password encryption — 5 algorithms: MD5/SHA/AES/RSA/BCrypt + TOTP verification codes
- Session queries — SaTerminalInfo terminal lists + searchTokenValue/TokenSession/Session
- HTTP Basic/Digest — @SaCheckHttpBasic / @SaCheckHttpDigest
- Firewall — IP allowlists and blocklists + request rate limiting
- Custom annotations — composite annotations/custom authorization annotations
⚠️ Requirements
- All features are based on , and some features require the user to be logged in first
- Global listeners must be registered in the Spring container (@Component or manual registration)
- Multi-account authentication requires you to define your own account system names
❌ Out of Scope
- Basic login/permissions/annotation authorization → sa-token
- SSO single sign-on → sa-token-sso
- OAuth 2.0 server → sa-token-oauth2
- Microservice authentication and authorization → sa-token-micro
Reference Documentation
| Topic | File | Source |
|---|
| Secondary authentication (safe-auth) | references/safe-auth.md | GitHub |
| Account banning (category-specific + tiered) | references/disable.md | GitHub |
| Identity switching (mock-person) | references/mock-person.md | GitHub |
| Multi-account authentication | references/many-account.md | GitHub |
| Password encryption + HTTP Basic | references/password-basic.md | GitHub |
| Global listeners + global filters | references/listener-filter.md | GitHub |
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);
FAQ
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
. You can refer to the
package in the official demo.
Gotchas
- can implement custom ban logic through — default bans are stored in memory and are lost after a restart
- Multi-account systems can specify the account system through the attribute in annotations — for example,
@SaCheckLogin(type = "user")
- Using is recommended for global listeners — override only the methods you need
- Secondary authentication has a default validity period of 120 seconds — adjust it according to your business requirements
- A higher tiered-ban level means a more severe ban — blocks access only when level≥3
- The Lambda form of switchTo is safer than manually calling endSwitch — it prevents you from forgetting to restore the original identity
- When configuring security response headers through a global filter, account for browser compatibility
- HTTP Basic credentials are transmitted in plaintext over the network — use it together with HTTPS
Data Privacy
This skill does not collect, store, or transmit any user data. All code examples are provided for local development reference only.