npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

sa-token

v1.0.8

Published

第一版,由java版satoken转换而来,java版本1.44.0

Readme

Sa-Token Node.js SDK 发布文档

项目概述

Sa-Token 是一个轻量级的 Java 权限认证框架,而 sa-token-node 是其 Node.js 版本的实现。该 SDK 提供了完整的权限认证解决方案,包括登录认证、权限验证、会话管理、临时令牌、安全防护等功能。

核心功能

  • 🔐 登录认证 - 完整的登录认证机制,支持多端登录
  • 👥 权限验证 - 角色、权限、路径等多维度权限控制
  • 📦 会话管理 - 强大的 Session 管理功能
  • 🔒 安全防护 - 内置防火墙、请求校验等安全机制
  • 高性能 - 基于内存缓存和定时清理机制
  • 🧩 插件扩展 - 模块化设计,支持灵活的功能扩展
  • 🌐 多框架适配 - 支持 Express、Koa 等主流 Node.js 框架

安装步骤

前置要求

  • Node.js >= 18.0.0
  • npm 或 yarn 包管理器

安装方式

# 使用 npm 安装
npm install sa-token

# 使用 yarn 安装
yarn add sa-token

导入模块

// ES6 模块导入
import { StpUtil, SaManager } from 'sa-token-node';

// CommonJS 导入
const { StpUtil, SaManager } = require('sa-token-node');

使用方法

基础配置

import { SaManager, SaTokenConfig } from 'sa-token-node';

// 创建配置对象
const config = new SaTokenConfig();
config.tokenName = "satoken";
config.timeout = 2592000; // 30天
config.activityTimeout = -1;
config.isConcurrent = true;
config.isShare = true;

// 设置配置
SaManager.setConfig(config);

登录认证

import { StpUtil } from 'sa-token-node';

// 用户登录
StpUtil.login(10001);

// 获取当前登录用户ID
const loginId = StpUtil.getLoginId();

// 获取Token信息
const tokenInfo = StpUtil.getTokenInfo();

// 用户登出
StpUtil.logout();

权限验证

import { StpUtil } from 'sa-token-node';

// 角色验证
StpUtil.checkRole("admin");

// 权限验证
StpUtil.checkPermission("user:add");

// 路径验证
StpUtil.checkPath("/user/list");

会话管理

import { StpUtil } from 'sa-token-node';

// 获取当前会话
const session = StpUtil.getSession();

// 设置会话属性
session.set("userInfo", { name: "张三", age: 18 });

// 获取会话属性
const userInfo = session.get("userInfo");

项目结构

sa-token-node/
├── sa-token/
│   ├── application/      # 应用相关接口
│   ├── config/           # 配置相关类
│   ├── context/          # 上下文处理
│   ├── dao/              # 数据访问层
│   ├── exception/        # 异常处理
│   ├── filter/           # 过滤器
│   ├── http/             # HTTP工具
│   ├── listener/         # 监听器
│   ├── log/              # 日志处理
│   ├── plugin/           # 插件系统
│   ├── router/           # 路由处理
│   ├── secure/           # 安全工具
│   ├── serializer/       # 序列化处理
│   ├── session/          # 会话管理
│   ├── stp/              # 核心认证逻辑
│   ├── strategy/         # 策略模式
│   ├── temp/             # 临时令牌
│   └── util/             # 工具类
└── index.js              # 入口文件

核心模块介绍

认证核心模块

  • StpUtil - 权限认证工具类,提供登录、权限验证等核心功能
  • SaManager - 全局管理器,负责配置管理和组件协调
  • SaTokenConfig - 配置类,管理认证相关配置参数

上下文模块

  • SaTokenContext - 上下文接口,定义请求、响应、存储等上下文操作
  • SaRequest/SaResponse - 请求响应模型
  • SaStorage - 存储模型

数据访问模块

安全防护模块

扩展模块

API 文档

核心认证 API

| 方法 | 描述 | 参数 | 返回值 | |------|------|------|--------| | StpUtil.login(id) | 用户登录 | id: 用户标识 | void | | StpUtil.checkLogin() | 验证是否登录 | 无 | void | | StpUtil.getLoginId() | 获取当前登录用户ID | 无 | Object | | StpUtil.logout() | 用户登出 | 无 | void | | StpUtil.getTokenInfo() | 获取Token信息 | 无 | SaTokenInfo |

权限验证 API

| 方法 | 描述 | 参数 | 返回值 | |------|------|------|--------| | StpUtil.hasRole(role) | 判断是否具有角色 | role: 角色标识 | boolean | | StpUtil.checkRole(role) | 验证角色权限 | role: 角色标识 | void | | StpUtil.hasPermission(permission) | 判断是否具有权限 | permission: 权限标识 | boolean | | StpUtil.checkPermission(permission) | 验证权限 | permission: 权限标识 | void |

会话管理 API

| 方法 | 描述 | 参数 | 返回值 | |------|------|------|--------| | StpUtil.getSession() | 获取当前会话 | 无 | SaSession | | StpUtil.getSessionByLoginId(loginId) | 根据登录ID获取会话 | loginId: 用户标识 | SaSession | | session.set(key, value) | 设置会话属性 | key,value: 键值对 | void | | session.get(key) | 获取会话属性 | key: 属性键 | Object |

配置说明

主要配置项

const config = new SaTokenConfig();
config.tokenName = "satoken";            // Token名称
config.timeout = 2592000;                // Token有效期(单位: 秒)
config.activityTimeout = -1;             // Token最小活跃时间
config.isConcurrent = true;              // 是否允许同一账号并发登录
config.isShare = true;                   // 在多个浏览器共用一个Token
config.isReadCookie = true;              // 是否从Cookie中读取Token
config.isReadHead = true;                // 是否从请求头里读取Token
config.isReadBearer = true;              // 是否从Bearer中读取Token

Cookie 配置

const cookieConfig = new SaCookieConfig();
cookieConfig.path = "/";                 // Cookie作用路径
cookieConfig.domain = "";                // Cookie作用域
cookieConfig.secure = false;             // 是否只在https下传输
cookieConfig.httpOnly = false;           // 是否禁止js操作Cookie
cookieConfig.sameSite = "";              // SameSite设置

异常处理

常见异常类型

异常处理示例

import { NotLoginException } from 'sa-token-node';

try {
    StpUtil.checkLogin();
} catch (e) {
    if (e instanceof NotLoginException) {
        // 处理未登录情况
        console.log("用户未登录");
    }
}

扩展功能

自定义实现

// 自定义Token持久化
class CustomTokenDao extends SaTokenDao {
    // 实现自定义存储逻辑
}

// 自定义权限接口
class CustomStpInterface extends StpInterface {
    // 实现自定义权限获取逻辑
}

插件系统

import { SaTokenPlugin } from 'sa-token-node';

class MyPlugin extends SaTokenPlugin {
    // 插件实现
}

// 注册插件
SaManager.registerPlugin(new MyPlugin());

最佳实践

1. 配置初始化

在应用启动时进行统一配置:

import { SaManager, SaTokenConfig } from 'sa-token-node';

const config = new SaTokenConfig();
config.tokenName = "Authorization";
config.timeout = 7 * 24 * 60 * 60; // 7天
config.isConcurrent = false; // 禁止并发登录

SaManager.setConfig(config);

2. 中间件集成

// Express 中间件示例
app.use((req, res, next) => {
    // 设置上下文
    SaManager.setTokenContext(new MyTokenContext(req, res));
    next();
});

3. 全局异常处理

// 统一异常处理
app.use((err, req, res, next) => {
    if (err instanceof NotLoginException) {
        res.status(401).json({ code: 401, msg: "未登录" });
    } else {
        next(err);
    }
});

性能优化建议

  1. 合理设置超时时间 - 根据业务场景设置合适的Token超时时间
  2. 使用分布式存储 - 在集群部署时使用Redis等分布式存储
  3. 启用Token共享 - 对于多端应用可启用Token共享减少重复登录
  4. 避免频繁权限检查 - 可将权限信息缓存到Session中减少重复查询

版本更新日志

(需要开发者提供具体版本信息)

技术支持

  • GitHub Issues: [github.com/yijiu2025/sa-token-node]
  • 官方文档: [文档地址]
  • 社区交流: [交流群/论坛地址]

许可证

"Apache-2.0" License