Simplify Spring Boot Authentication with Sa-Token: A Complete Guide
This article introduces Sa-Token, a lightweight Java authentication framework, explains why it outperforms Spring Security, shows how to configure it in Spring Boot, and provides multiple code examples—including login, logout, role and permission checks, global interceptors, front‑end token handling, and Redis storage.
Overview
Login authentication, permission control, and session management are fundamental requirements for enterprise back‑end systems. Traditional solutions such as Spring Security are powerful but have a steep learning curve, complex configuration, and can be heavyweight for small‑to‑medium projects.
Sa‑Token is a lightweight Java permission framework designed to simplify these concerns.
Why Choose Sa‑Token?
Intuitive, zero‑intrusive API.
Supports login authentication, permission checks, and role management.
Provides both Token and Session modes.
Native support for front‑end/back‑end separation.
Integrates with Redis, JWT, and multi‑device login.
Active community and clear documentation.
Core Design Idea
Request
↓
Sa‑Token Interceptor
↓
Login / Permission Check
↓
ControllerThe framework performs permission checks through method annotations rather than extensive XML or property configuration.
Sa‑Token Configuration
Maven Dependency
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-spring-boot3-starter</artifactId>
<version>1.38.0</version>
</dependency>Basic application.yml Settings
sa-token:
token-name: satoken # Header name
timeout: 2592000 # 30 days (seconds)
activity-timeout: -1 # Disable activity timeout
is-concurrent: true # Allow concurrent login
is-share: true # Share token across multiple devices
token-style: uuid # Token format
is-log: true # Enable loggingPractical Examples
Login / Logout Endpoints
@RestController
@RequestMapping("/auth")
public class AuthController {
@PostMapping("/login")
public String login(String username, String password) {
// Simple validation example
if ("admin".equals(username) && "123456".equals(password)) {
StpUtil.login(10001); // Login with user ID 10001
return "登录成功";
}
return "登录失败";
}
@PostMapping("/logout")
public String logout() {
StpUtil.logout();
return "退出成功";
}
}After a successful login, Sa‑Token returns a token that the front‑end must include in subsequent requests, e.g.:
satoken: 9a3b2dxx-xxxx-xxxxLogin Validation in Controllers
@SaCheckLogin
@GetMapping("/user/info")
public String userInfo() {
return "当前登录用户:" + StpUtil.getLoginId();
}If the request is not authenticated, Sa‑Token throws an NotLoginException automatically.
Role Validation
Bind a role when logging in (optional, can be stored in session):
StpUtil.login(10001);
StpUtil.getSession().set("role", "admin");Implement a custom StpInterface to provide role and permission data from a database or other source:
@Component
public class StpInterfaceImpl implements StpInterface {
@Override
public List<String> getRoleList(Object loginId, String loginType) {
// Example: return roles for the given user
return List.of("admin");
}
@Override
public List<String> getPermissionList(Object loginId, String loginType) {
// Example: return permissions for the given user
return List.of("user:add", "user:delete");
}
}Use the role annotation on controller methods:
@SaCheckRole("admin")
@GetMapping("/admin")
public String admin() {
return "管理员访问成功";
}Permission Validation
@SaCheckPermission("user:add")
@PostMapping("/user/add")
public String addUser() {
return "新增用户成功";
}Global Route Interceptor (Recommended)
@Configuration
public class SaTokenConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SaInterceptor(handler -> StpUtil.checkLogin()))
.addPathPatterns("/**")
.excludePathPatterns("/auth/login");
}
}This interceptor enforces login for all routes except the login endpoint, removing the need to annotate every controller method.
Front‑End / Back‑End Separation
axios.defaults.headers.common['satoken'] = localStorage.getItem("token");Front‑end frameworks can store the token in localStorage and automatically attach it to each request.
Redis Token Storage (Production Recommendation)
Add the Redis DAO dependency:
<dependency>
<groupId>cn.dev33</groupId>
<artifactId>sa-token-dao-redis</artifactId>
<version>1.38.0</version>
</dependency>Configure Redis connection in application.yml:
spring:
data:
redis:
host: localhost
port: 6379When the Redis dependency is present, Sa‑Token automatically switches token storage to Redis, enabling distributed session management.
Summary
Implement login, role, and permission control with minimal configuration.
Leverage annotation‑driven checks or a global interceptor for flexible security policies.
Optionally use Redis for token persistence in clustered environments.
Sample project repository (clone with Git): https://gitee.com/lhdxhl/springboot3-example.git
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
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.
