Backend Development 23 min read

Sa-Token Java Permission Authentication Framework: Overview, Login, and Permission Implementation

This article introduces the lightweight Sa-Token Java authentication framework, explains why it is chosen over Spring Security and Shiro, details its login and permission APIs with code examples, shows how to configure it in Spring Boot and WebFlux projects, and lists its extensive feature set for secure backend development.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
Sa-Token Java Permission Authentication Framework: Overview, Login, and Permission Implementation

Technical Selection

When implementing login and authorization, Spring Boot + Spring Security was considered too heavy, and Spring Boot + Shiro conflicted with Spring AOP, so Sa-Token was chosen as a lightweight alternative.

Sa-Token Overview

Sa-Token is a lightweight Java permission authentication framework that solves login authentication, permission authentication, single sign‑on, OAuth2.0, distributed session, micro‑service gateway authentication and many other permission‑related problems.

Login Authentication

The typical flow is: the user submits name and password , the server validates them, issues a token (session credential) and returns it via a Cookie.

Session login can be performed with a single line of code:

// 会话登录:参数填写要登录的账号id,建议的数据类型:long | int | String, 不可以传入复杂类型,如:User、Admin 等
StpUtil.login(Object id);

Example login controller:

// 会话登录接口
@RequestMapping("doLogin")
public SaResult doLogin(String name, String pwd) {
    // 第一行:比对前端提交的账号名称、密码
    if ("zhang".equals(name) && "123456".equals(pwd)) {
        // 第二步:根据账号id,进行登录
        StpUtil.login(10001);
        return SaResult.ok("登录成功");
    }
    return SaResult.error("登录失败");
}

Sa-Token uses Cookie to automatically inject the token, so the token does not need to be manually returned.

Additional session APIs:

// 当前会话注销登录
StpUtil.logout();
// 获取当前会话是否已经登录,返回 true=已登录,false=未登录
StpUtil.isLogin();
// 检验当前会话是否已经登录, 未登录则抛出 NotLoginException
StpUtil.checkLogin();

Permission Authentication

Permission checking determines whether an account possesses a specific permission code.

Custom permission list can be provided by implementing StpInterface :

/**
 * 自定义权限验证接口扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {
    @Override
    public List
getPermissionList(Object loginId, String loginType) {
        List
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
getRoleList(Object loginId, String loginType) {
        List
list = new ArrayList<>();
        list.add("admin");
        list.add("super-admin");
        return list;
    }
}

Permission APIs:

// 获取当前账号的权限集合
StpUtil.getPermissionList();
// 判断是否拥有指定权限,返回 true/false
StpUtil.hasPermission("user-update");
// 校验权限,未通过抛出 NotPermissionException
StpUtil.checkPermission("user-update");
// 多权限且全部通过
StpUtil.checkPermissionAnd("user-update", "user-delete");
// 多权限任意一个通过
StpUtil.checkPermissionOr("user-update", "user-delete");

Role APIs work similarly with hasRole , checkRole , etc.

Wildcard permissions such as user* match all user‑related codes, and * grants all permissions.

Global Exception Handling

@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public SaResult handlerException(Exception e) {
        e.printStackTrace();
        return SaResult.error(e.getMessage());
    }
}

Front‑end Button‑Level Control

When using a front‑end framework (e.g., Vue), store the permission list returned after login and conditionally render buttons:

<button v-if="arr.indexOf('user:delete') > -1'">删除按钮</button>

Feature Overview

Login authentication (single‑device, multi‑device, exclusive login, remember‑me)

Permission & role authentication, session secondary authentication

Distributed session, token sharing, SSO, OAuth2.0, JWT, etc.

Session management, kick‑out, account banning, persistent storage (Redis, Memcached)

Annotation‑based and route‑based authentication, automatic token renewal

Various starter packages for Spring MVC, WebFlux, Solon, JFinal, etc.

Using Sa-Token in a Spring Boot Project

Dependency

Maven:

cn.dev33
sa-token-spring-boot-starter
1.30.0

Gradle:

implementation 'cn.dev33:sa-token-spring-boot-starter:1.30.0'

Configuration (application.yml)

server:
  port: 8081
sa-token:
  token-name: satoken
  timeout: 2592000
  activity-timeout: -1
  is-concurrent: true
  is-share: false
  token-style: uuid
  is-log: false

Sample Application

@SpringBootApplication
public class SaTokenDemoApplication {
    public static void main(String[] args) throws JsonProcessingException {
        SpringApplication.run(SaTokenDemoApplication.class, args);
        System.out.println("启动成功:Sa-Token配置如下:" + SaManager.getConfig());
    }
}

Test 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();
    }
}

Running the Demo

Start the application and access http://localhost:8081/user/doLogin?username=zhang&password=123456 to log in, then /user/isLogin to check the session status.

Conclusion

Sa-Token is a lightweight, feature‑rich authentication and authorization framework that simplifies secure backend development in Java.

backendJavaSpring BootsecurityAuthenticationauthorizationSa-Token
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.