SuperAPI AI Directory

sa-token

Coding & development

View repository

Updated 10-15 21:48

About this skill

Sa-Token Core Authentication Framework

Based on Sa-Token v1.45.0 | Official documentation:https://sa-token.cc | GitHub:https://github.com/dromara/sa-token

Sa-Token is a lightweight Java authentication framework with zero dependencies in its core package, providing a complete authentication system.StpUtil is its core facade utility class.

Capability Boundaries

✅ Strong Suits

  1. Login Authentication — StpUtil.login() session login, remember-me mode, specifying device type, login extension parameters
  2. Session Validation — StpUtil.isLogin()/checkLogin()/getLoginId() full set of query APIs
  3. Token Management — get token value/name/info, look up the account by token, dual token validity period policies (timeout + active-timeout)
  4. Permission/Role Authentication — implement StpInterface to define a permission loader, checkPermission/checkRole series APIs, permission wildcard *
  5. Annotation-Based Authorization — @SaCheckLogin、@SaCheckPermission、@SaCheckRole、@SaIgnore、@SaCheckOr
  6. Route Interception Authorization — SaInterceptor + SaRouter matching chain, stop/back/free exit mechanisms, multi-condition matching
  7. Session — three models: Account-Session / Token-Session / Custom-Session
  8. Kicking Users Offline — three operations: force logout, kick offline, and be displaced offline
  9. Framework Configuration — all application.yml configuration items, code-based configuration
  10. Front-End/Back-End Separation — Cookie mode vs Header mode, adaptation for Mini Programs/APPs without Cookies
  11. Custom Token — 6 built-in styles, custom generation strategy, Bearer submission prefix
  12. Mutually Exclusive Login on the Same Client — only one online session allowed for the same device type

❌ Out of Scope (Alternative Solutions)

  1. Secondary authentication/account banning/impersonating others/multiple accounts → sa-token-advanced
  2. SSO single sign-on → sa-token-sso
  3. OAuth2.0 server → sa-token-oauth2
  4. Microservice Same-Token/gateway authentication → sa-token-micro
  5. API signing/API Key/temporary Token → sa-token-api-security
  6. JWT integration/Redis persistence/template engine → sa-token-integration

Applicable Scenarios

Activate this skill when the user needs the following scenarios:

  • Integrating authentication into a new project — Introduce Sa-Token into a SpringBoot project, configure StpInterface, and implement login/permission validation
  • Adding authentication to an existing project — Add login validation/permission validation/role validation to existing APIs
  • Configuring a route interceptor — Uniformly intercept all requests and divide different authentication rules by module
  • Using annotation-based authorization — Use annotations such as @SaCheckLogin/@SaCheckPermission
  • Front-end/back-end separation adaptation — Transmission and validation of Tokens in Cookie-free environments
  • Debugging and troubleshooting — Troubleshoot various NotLoginException scenario values and Token validity period issues

Workflow

Step 1. Introduce dependencies — Add sa-token-spring-boot-starter dependencies (choose according to the SpringBoot version) Step 2. Configure the framework — Configure token name, validity period, style, etc. in application.yml Step 3. Implement StpInterface — Custom permission loader, returning permission codes and role collections Step 4. Login authentication — Call StpUtil.login(id) to complete session login Step 5. Permission verification — Use StpUtil methods or annotations for permission/role verification Step 6. Route interception — Implement global route authentication with SaInterceptor + SaRouter Step 7. Integration testing — Verify the complete login/logout/permission verification/annotation authentication process

StpUtil core API quick reference

// === 登录认证 ===
StpUtil.login(Object loginId);                          // 会话登录
StpUtil.login(10001, "PC");                             // 指定设备类型
StpUtil.login(10001, true);                             // 指定记住我
StpUtil.login(10001, new SaLoginParameter()...);        // 完整参数模式
StpUtil.logout();                                       // 当前会话注销
StpUtil.logout(10001);                                  // 指定账号注销
	StpUtil.logoutByTokenValue(token);                      // 指定Token注销
	StpUtil.logoutByLoginId(10001, "PC");                   // 指定账号+设备注销
	StpUtil.kickout(10001);                                 // 踢人下线
	StpUtil.kickoutByTokenValue(token);                     // 根据Token值踢人
StpUtil.isLogin();                                      // 是否登录(true/false)
StpUtil.checkLogin();                                   // 校验登录(未登录抛NotLoginException)

	// === 会话/Token查询 ===
	StpUtil.getLoginId();                                   // 当前账号id
	StpUtil.getLoginIdAsString()/AsInt()/AsLong();          // 类型化获取
	StpUtil.getLoginIdDefaultNull();                        // 未登录返回null
	StpUtil.getLoginIdByToken(token);                       // 根据token查账号
	StpUtil.getTokenValue();                                // 当前token值
	StpUtil.getTokenValueByLoginId(10001);                  // 获取指定账号的token值
	StpUtil.getTokenListByLoginId(10001);                   // 获取指定账号所有token列表
	StpUtil.getTokenName();                                 // token名称(satoken)
	StpUtil.getTokenTimeout();                              // 剩余有效期(秒)
	StpUtil.getTokenInfo();                                 // 完整TokenInfo
	StpUtil.setTokenValue("xxx-xxx");                       // 手动设置当前会话token值
	StpUtil.renewRefresh();                                // 自动续签token有效期
	StpUtil.getTerminalListByLoginId(10001);                // 获取指定账号所有终端列表

	// === 权限/角色校验 ===
	StpUtil.getPermissionList();                            // 权限码集合
	StpUtil.hasPermission("user.add");                     // boolean
	StpUtil.checkPermission("user.add");                   // 失败抛NotPermissionException
	StpUtil.checkPermissionAnd("add","del","get");          // 全部拥有
	StpUtil.checkPermissionOr("add","del","get");          // 至少一个
	StpUtil.hasRole("admin");                               // boolean
	StpUtil.checkRole("admin");                             // 失败抛NotRoleException
	
	// === Session会话 ===
	StpUtil.getSession();                                   // 当前账号Account-Session
	StpUtil.getSessionByLoginId(10001);                     // 指定账号的Session
	StpUtil.getTokenSession();                              // 当前Token-Session
	StpUtil.getTokenSessionByTokenValue("xxx-xxx");        // 按token值获取Token-Session
	SaSessionCustomUtil.getSessionById("goods-10001");     // Custom-Session

Reference documentation

Topic File Source
Complete guide to login authentication references/login-auth.md GitHub
Permission/role authentication references/jur-auth.md GitHub
Annotation authentication references/at-check.md GitHub
Route interception authentication references/route-check.md GitHub
Session references/session.md GitHub
Framework configuration references/config.md GitHub
Kick user offline references/kickout.md GitHub
Token validity period references/token-timeout.md GitHub
NotLoginException references/not-login-scene.md GitHub
Frontend-backend separation & remember me references/not-cookie.md GitHub、remember-me
Token style & prefix references/token-style.md GitHub、token-prefix
Detailed explanation of login parameters references/login-parameter.md GitHub
Mutually exclusive login on the same client references/mutex-login.md GitHub
Quick start examples/quickstart.md GitHub

Gotchas

  1. StpInterface does not execute at startup — It only triggers a query when an authentication method is called
  2. Annotation authentication is disabled by default — Must manually register SaInterceptor
  3. SaSession ≠ HttpSession — The two have no relationship at all, do not confuse them
  4. Frontend authentication is only auxiliary — It cannot replace backend verification
  5. @SaIgnore only takes effect for SaInterceptor and AOP — Custom interceptors are not affected
  6. @SaCheckPermission defaults to AND mode — OR mode requires specifying mode = SaMode.OR
  7. StpUtil.logout() logout scope can be controlled via logout-range configuration — By default only the current token is logged out
  8. Cookie mode injects Cookie by default — Can be disabled with is-read-cookie: false

Data Privacy

This skill does not collect, store, or transmit any user data.