Master Sa-Token: Lightweight Java Authentication & Authorization for Secure Backend Development
This article introduces Sa-Token, a lightweight Java permission authentication framework, explains its core features such as login, token handling, permission and role checks, demonstrates practical code snippets, and provides step‑by‑step integration guides for Spring Boot and WebFlux projects.
1. Technical Selection
When implementing login and authorization, Spring Boot + Spring Security is often too heavyweight for lightweight projects, and Spring Boot + Shiro conflicts with Spring Boot's AOP. Sa-Token is introduced as a suitable alternative.
2. Sa-Token Overview
2.1 Simple Introduction
Sa-Token is a lightweight Java permission authentication framework that solves login authentication, permission authentication, single sign‑on, OAuth2.0, distributed session, and other related issues.
Login authentication
Permission authentication
Single sign‑on
OAuth2.0
Distributed Session
Microservice gateway authentication
2.2 Login Authentication
Design Idea
Protected APIs require a login check. The login flow involves the client submitting credentials, the server returning a token, and subsequent requests carrying this token for verification.
Login and Logout
StpUtil.login(Object id);This single line logs in a session, handling checks for bans, existing logins, token generation, global listeners, and token injection into the request context.
@RequestMapping("doLogin")
public SaResult doLogin(String name, String pwd) {
if ("zhang".equals(name) && "123456".equals(pwd)) {
StpUtil.login(10001);
return SaResult.ok("登录成功");
}
return SaResult.error("登录失败");
}Sa-Token uses cookies to automatically store and submit the token, so the token does not need to be manually returned.
Session Queries
// Get current session login ID
StpUtil.getLoginId();
// Get token value
StpUtil.getTokenValue();
// Get token info (JSON structure)2.3 Permission Authentication
Design Idea
Permission checks verify whether an account possesses a specific permission code. The framework checks the account's permission set against the required code.
// Check if current account has permission
StpUtil.hasPermission("user-update");
// Enforce permission, throws NotPermissionException if missing
StpUtil.checkPermission("user-update");Custom Permission Retrieval
@Component
public class StpInterfaceImpl implements StpInterface {
@Override
public List<String> getPermissionList(Object loginId, String loginType) {
List<String> list = new ArrayList<>();
list.add("101");
list.add("user-add");
list.add("user-delete");
list.add("user-update");
list.add("user-get");
list.add("article-get");
return list;
}
@Override
public List<String> getRoleList(Object loginId, String loginType) {
List<String> list = new ArrayList<>();
list.add("admin");
list.add("super-admin");
return list;
}
}Role Authentication
// Check role
StpUtil.hasRole("super-admin");
// Enforce role, throws NotRoleException if missing
StpUtil.checkRole("super-admin");Global Exception Interception
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler
public SaResult handlerException(Exception e) {
e.printStackTrace();
return SaResult.error(e.getMessage());
}
}Permission Wildcards
// When having "user*" permission
StpUtil.hasPermission("user-add"); // true
StpUtil.hasPermission("user-update"); // true
StpUtil.hasPermission("art-add"); // falseButton‑Level Permission Control
In front‑end projects, return the full permission set after login and let the UI hide or show buttons based on the presence of specific codes, e.g., in Vue:
<button v-if="arr.indexOf('user:delete') > -1'">Delete</button>Why Backend Still Needs Authorization
Front‑end checks can be bypassed; the backend must always enforce permission verification to ensure security.
3. Feature Overview
Login authentication (single‑device, multi‑device, remember‑me, etc.)
Permission & role authentication
Session management (shared, exclusive, custom)
Kick‑out, account banning, persistent storage
Distributed session (JWT, shared data center)
Gateway authentication (Gateway, ShenYu, Zuul)
SSO, OAuth2.0, secondary authentication
Basic auth, token styles, global listeners
Spring MVC, WebFlux starters, and many plugins
4. Sa-Token Usage
4.1 Adding Dependency
<!-- Maven -->
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot-starter</artifactId>
<version>1.30.0</version>
</dependency>
<!-- Gradle -->
implementation 'cn.dev33:sa-token-spring-boot-starter:1.30.0'4.2 Spring Boot Integration Example
Application Class
@SpringBootApplication
public class SaTokenDemoApplication {
public static void main(String[] args) throws JsonProcessingException {
SpringApplication.run(SaTokenDemoApplication.class, args);
System.out.println("启动成功:Sa-Token配置如下:" + SaManager.getConfig());
}
}Controller
@RestController
@RequestMapping("/user/")
public class UserController {
@RequestMapping("doLogin")
public String doLogin(String username, String password) {
if ("zhang".equals(username) && "123456".equals(password)) {
StpUtil.login(10001);
return "登录成功";
}
return "登录失败";
}
@RequestMapping("isLogin")
public String isLogin() {
return "当前会话是否登录:" + StpUtil.isLogin();
}
}4.3 WebFlux Integration Example
Global Filter
@Configuration
public class SaTokenConfigure {
@Bean
public SaReactorFilter getSaReactorFilter() {
return new SaReactorFilter()
.addInclude("/**")
.addExclude("/favicon.ico")
.setAuth(obj -> System.out.println("---------- sa全局认证"))
.setError(e -> {
System.out.println("---------- sa全局异常 ");
return SaResult.error(e.getMessage());
});
}
}WebFlux Controller
@RestController
@RequestMapping("/user/")
public class UserController {
@RequestMapping("doLogin")
public String doLogin(String username, String password) {
if ("zhang".equals(username) && "123456".equals(password)) {
StpUtil.login(10001);
return "登录成功";
}
return "登录失败";
}
@RequestMapping("isLogin")
public String isLogin() {
return "当前会话是否登录:" + StpUtil.isLogin();
}
}5. Conclusion
Sa-Token is a lightweight, easy‑to‑integrate Java framework for login, authentication, and permission management, making secure backend development straightforward.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
