@easyweb/authentication

中文文档
2.2.0发布于 2026/08/27MITTypeScriptESM + CJS零依赖近 30 天下载 3439

Shared authentication primitives for Easyweb microservices: stateless JWT middleware, request context, and token verification helpers

原始使用文档
文档目录8 节
  1. 2.1.0 — SUPER_ADMIN now satisfies authorize(["ADMIN"])
  2. Upgrading to 2.0.0 — BREAKING
  3. Install
  4. Usage
  5. What it verifies — and what it does not
  6. Exports
  7. Token contract
  8. License

@easyweb/authentication

Shared authentication primitives for Easyweb microservices — stateless JWT middleware, request-context middleware, and the token verification helpers services build on.

Companion to @easyweb/events for messaging, and @easyweb/errors for the HTTP error taxonomy.

2.1.0 — SUPER_ADMIN now satisfies authorize(["ADMIN"])

authorize() was an exact string match. Every admin route in the platform is written authorize(["ADMIN"]), and auth-service's admin-seed.ts grants the bootstrap operator SUPER_ADMIN by default — so the seeded account could not call a single admin route on the platform.

SUPER_ADMIN now implies ADMIN. Nothing else implies anything: ADMIN deliberately does not imply USER, because that edge would silently widen every future customer route to staff.

Additive, and widening only. A service still on 2.0.0 behaves exactly as it did — SUPER_ADMIN simply stays locked out there — so this needs no coordinated deploy. Since every service declares ^2.0.0 but installs from a lockfile, pick it up with:

npm i @easyweb/authentication@^2.1.0

The new effectiveRoles(roles) export does the same expansion for a service with its own guard (auth-service's DB-backed middleware, in particular).

The status is unchanged: authorize() still throws NotAuthorizedError, which is 401 even for a signed-in caller with the wrong role. Every service's http suite pins that. A caller needing to tell "not signed in" from "not permitted" must check the role itself.

Upgrading to 2.0.0 — BREAKING

The error classes moved to @easyweb/errors. Error handling is cross-cutting and has nothing to do with JWTs; a service needing ConflictError should not have to depend on an auth package for it.

- import { NotAuthorizedError } from "@easyweb/authentication";
+ import { NotAuthorizedError } from "@easyweb/errors";

@easyweb/errors is a peerDependency — install it alongside this package. Do not let it end up nested under node_modules/@easyweb/authentication/: two copies of CustomError means instanceof fails across the boundary and the error handler answers 500 for everything, with no type error to warn you. Verify with npm ls @easyweb/errors.

Also new in 2.0.0: extractToken and isValidAccessPayload are exported, for services that keep their own DB-backed middleware (see below) and would otherwise copy them.

Install

npm install @easyweb/authentication

express@^5 and jsonwebtoken@^9 are peer dependencies — the consuming service provides them.

Usage

Nothing in this package reads process.env. Config is bound once at startup, so the package never has to reach into a service's config module.

import express from "express";
import cookieParser from "cookie-parser";
import { createAuthMiddleware, requestContext } from "@easyweb/authentication";
import config from "./config";

const app = express();
app.use(cookieParser()); // required: the middleware reads the accessToken cookie
app.use(requestContext);

const authMiddleware = createAuthMiddleware(config.jwt);
// config.jwt must supply { secret, issuer, audience } matching auth-service's

app.get("/me", authMiddleware.authenticate, (req, res) => {
  res.json(req.user); // { id, email, username, roles, permissions }
});

app.get("/feed", authMiddleware.optionalAuth, (req, res) => {
  res.json({ personalised: Boolean(req.user) });
});

app.delete(
  "/admin/:id",
  authMiddleware.authenticate,
  authMiddleware.authorize(["admin"]),
  handler,
);

Minting tokens (auth-service only):

import { createJwtSigner } from "@easyweb/authentication";

const signAccessToken = createJwtSigner(config.jwt);
// config.jwt additionally needs accessTokenTtlSeconds

What it verifies — and what it does not

authenticate is stateless. It checks the signature, issuer, audience, expiry, and that the payload is a well-formed access token. It performs no database lookup.

A logout or session revoke in auth-service stays invisible here until the access token expires (JWT_ACCESS_TOKEN_TTL_SECONDS, currently 300). If a service needs immediate revocation, it must keep its own DB-backed middleware — auth-service does exactly that.

req.user.permissions is always []. The access token carries no permissions claim; auth-service resolves those from its own tables at request time. Guarding on this array would deny every request.

Exports

ExportPurpose
createAuthMiddleware(config){ authenticate, optionalAuth, authorize }
requestContextpropagates / generates x-request-id
createJwtVerifier(config)(token) => JwtAccessPayload, throws on invalid
createJwtSigner(config)(claims) => string
extractToken(req)Bearer header, then the accessToken cookie
isValidAccessPayload(decoded)type guard: is this a well-formed access token?
effectiveRoles(roles)the roles held, expanded through the implication map (2.1.0)
effectiveRoles(roles)the roles held, expanded through the implication map (2.1.0)
JwtAccessPayload, JwtAccessClaims, JwtVerifyConfig, JwtSignConfigtypes

extractToken and isValidAccessPayload exist for services that must keep a DB-backed middleware. They were previously private, so auth-service copied them — and the copies drifted. If you need the same checks with different error messages, import these rather than reimplementing them.

Importing the package also augments Express.Request with user, auth, and requestId. Remove any local copy of that declare global block or TypeScript will report duplicate members.

Token contract

JwtAccessPayload is the only shape the services agree on. Changing it breaks every consumer — bump the major version.

License

MIT

版本与发布记录

@easyweb/authentication 共发布 4 个版本,首次发布于 2026/08/06;过去 12 个月发布了 4 个版本。

版本发布日期距今
2.2.0latest2026/08/272 个月前
2.1.02026/08/172 个月前
2.0.02026/08/063 个月前
1.0.02026/08/063 个月前

关于 @easyweb/authentication 的常见问题

@easyweb/authentication 是什么?

Shared authentication primitives for Easyweb microservices: stateless JWT middleware, request context, and token verification helpers

如何安装 @easyweb/authentication?

在项目目录运行 npm install @easyweb/authentication,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@easyweb/errors(^1.0.0)、@easyweb/logging(^1.0.0)、express(^5.0.0)、jsonwebtoken(^9.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@easyweb/authentication 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@easyweb/authentication 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@easyweb/authentication 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@easyweb/authentication 可以商用吗?

@easyweb/authentication 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@easyweb/authentication 的下载量有多少?

根据 npm 官方下载统计,@easyweb/authentication 在 2026/10/13 – 2026/11/11 这 30 天内被下载 3,439 次,日均约 115 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@easyweb/authentication 还在维护吗?

最新版本 2.2.0 发布于 2026/08/27(2 个月前);至今共发布 4 个版本,其中过去 12 个月发布了 4 个;首次发布于 2026/08/06。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。