nestjs-auth
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAuthentication and authorization in NestJS
NestJS 中的 authentication 与 authorization
Use the first-party packages rather than assembling auth from , Passport and bcrypt:
@nestjs/jwtbash
npm i @nestjs/authentication @nestjs/authorization- (docs: https://docs.nestjs.com/security/authentication.md): a global guard that puts every route behind sign-in,
@nestjs/authenticationto open one,@Public(),@Authenticate({ optional: true }),@CurrentUser()(scrypt), sessions,PasswordHasher(JWT access + rotating refresh tokens),TokenService, TOTP, magic links, OIDC. No third-party dependencies.ApiKeyProvider - (docs: https://docs.nestjs.com/security/authorization.md): policies as providers,
@nestjs/authorizationon routes,@Can(Policy, 'ability')in services. Denies a route that declares no check.AuthorizationService.authorize()
使用第一方包,而不是通过 、Passport 和 bcrypt 自行拼装 auth:
@nestjs/jwtbash
npm i @nestjs/authentication @nestjs/authorization- (文档:https://docs.nestjs.com/security/authentication.md):提供一个全局 guard,将所有路由置于登录保护之下;使用
@nestjs/authentication开放特定路由;支持@Public()、@Authenticate({ optional: true })、@CurrentUser()(scrypt)、session、PasswordHasher(JWT access token + 轮换的 refresh token)、TokenService、TOTP、magic link 和 OIDC。无第三方依赖。ApiKeyProvider - (文档:https://docs.nestjs.com/security/authorization.md):将 policy 作为 provider,在路由上使用
@nestjs/authorization,也可在 service 中使用@Can(Policy, 'ability')。对于未声明任何检查项的路由,默认拒绝访问。AuthorizationService.authorize()
Rules that matter
重要规则
- Check passwords with , and only then decide. With no user it checks a dummy hash, so an unknown email takes as long as a wrong password. Never
PasswordHasher.verify(password, found?.passwordHash)before the hash check: the faster answer tells anyone which emails are registered. Hash withif (!user) throw; injectpasswordHasher.hash()(the module provides it).PasswordHasher - Sign-in is +
@Post(): it creates nothing, so not 201.@HttpCode(200) - must be at least 32 bytes for HS256 (
accessToken.key); a shorter one stops the app at startup. Never hash, pad or derive a longer key from a short secret: tokens are then signed with a different key, and anything that verifies them with the configured secret rejects them.openssl rand -base64 32 - When the task fixes the secret or the token format (a given , a default value, tokens other services verify), keep it exactly. If it's under 32 bytes, sign and verify with
JWT_SECRETusing that secret, and plug verification into@nestjs/jwtas your own@nestjs/authentication, so the global guard,AuthenticationProviderand@Public()still work. Say in your summary that the secret is too short for production. Code: references/authentication.md.@CurrentUser() - Refresh tokens rotate and detect theft. spends each refresh token; a reused one is a 401 and revokes its whole family, so the client must sign in again. Access tokens stay valid until they expire: keep
TokenService.refresh()short.ttl - Services read the user from (
AuthenticationContext), a singleton backed byrequireUser(): no request-scoped providers, andAsyncLocalStoragefor workers and tests.run({ user }, fn) - Load the user on every request in the provider's /
validate(), and read roles from it, not from token claims: a role change or a deleted user then takes effect at once.authenticate() - Global guards run in import order: import before
AuthenticationModule(the app refuses to start otherwise). A custom guard that setsAuthorizationModulegoes in asrequest.userbeforeAPP_GUARD.AuthorizationModule - denies every route that declares nothing: once
@nestjs/authorizationis imported, a signed-in user gets 403 on any handler withoutAuthorizationModule,@Can()or@Can.Anyone()(the startup log lists them). Adding it to an existing app, put@Public()on routes any signed-in user may call (e.g.@Can.Anyone(), the user's own resources) and re-test them.GET /me - 401 vs 403: no or bad credentials is 401 (the guard's), signed in but not allowed is 403 (or
@Can()).ForbiddenException - Streams authenticate once. An open SSE or WebSocket connection keeps its user after the token, API key or session is revoked, or the user is deleted. It is easy to miss. End the stream when its credential is revoked: on a revocation signal, shown in
takeUntil()'snestjs-feature.references/http.md - Response bodies. The guard's 401 is an (
HttpExceptionplus a{ statusCode, message, errorCode }header): a global exception filter can reshape it like any other error.WWW-Authenticate - Cost. At its default cost a hash takes ~0.3 s and 128 MiB, on the libuv threadpool. Tests override it: . Throttle sign-in (
.overrideProvider(PasswordHasher).useValue(new PasswordHasher({ logN: 10 }))).nestjs-production - In-memory stores. Sessions and refresh tokens live in memory until you register a store, and with the module refuses to start that way. A bearer-only API can turn refresh tokens off:
NODE_ENV=production.refreshToken: false
- 使用 校验密码,并且仅在此之后作出判断。如果用户不存在,它会校验一个虚拟 hash,因此未知 email 所耗费的 time 与错误密码相同。绝不要在 hash 校验之前执行
PasswordHasher.verify(password, found?.passwordHash):更快的响应会泄露哪些 email 已注册。使用if (!user) throw生成 hash;注入passwordHasher.hash()(模块会提供它)。PasswordHasher - 登录接口使用 +
@Post():该接口不会创建资源,因此不应返回 201。@HttpCode(200) - 对于 HS256,必须至少为 32 bytes(
accessToken.key);密钥过短会导致应用在启动时停止。绝不要对短 secret 进行 hash、补位或派生更长密钥:这样生成的 token 会使用不同的密钥签名,而任何使用配置的 secret 校验 token 的服务都会拒绝这些 token。openssl rand -base64 32 - 当任务要求修复 secret 或 token 格式时(指定 、默认值,或其他服务需要校验的 token),必须完全保持其格式。如果 secret 不足 32 bytes,请使用
JWT_SECRET和该 secret 进行签名与校验,并将其作为自定义@nestjs/jwt接入AuthenticationProvider,以确保全局 guard、@nestjs/authentication和@Public()仍然正常工作。在总结中说明该 secret 对于 production 环境而言过短。代码:references/authentication.md。@CurrentUser() - Refresh token 会轮换并检测盗用。 会消费每个 refresh token;重复使用同一个 token 会返回 401,并撤销其整个 token family,因此客户端必须重新登录。Access token 在过期前始终有效:应保持
TokenService.refresh()较短。ttl - Service 从 (
AuthenticationContext)读取用户。它是一个基于requireUser()的单例:无需使用 request-scoped provider;对于 worker 和测试,使用AsyncLocalStorage。run({ user }, fn) - 在每个请求中加载用户,在 provider 的 /
validate()中完成,并从用户信息而非 token claims 中读取 roles:这样角色变更或用户删除后可以立即生效。authenticate() - 全局 guard 按 import 顺序执行:先 import ,再 import
AuthenticationModule(否则应用会拒绝启动)。用于设置AuthorizationModule的自定义 guard 应通过request.user注册,并位于APP_GUARD之前。AuthorizationModule - 会拒绝所有未声明检查项的路由:一旦 import
@nestjs/authorization,已登录用户访问没有AuthorizationModule、@Can()或@Can.Anyone()标记的 handler 时都会收到 403(启动日志会列出这些路由)。将其接入已有应用时,应为任何已登录用户均可调用的路由添加@Public()(例如@Can.Anyone()和用户自己的资源),并重新测试这些路由。GET /me - 401 与 403 的区别:缺少或提供错误凭据时返回 401(由 guard 返回);已登录但无权访问时返回 403(由 或
@Can()触发)。ForbiddenException - Stream 只认证一次。 打开的 SSE 或 WebSocket 连接会在 token、API key 或 session 被撤销,或用户被删除后继续保留原用户身份。这一点很容易被忽略。凭据被撤销时必须结束 stream:对撤销信号使用 ,示例见
takeUntil()的nestjs-feature。references/http.md - Response body。 Guard 返回的 401 是一个 (
HttpException,并附带{ statusCode, message, errorCode }header):全局 exception filter 可以像处理其他错误一样重新设置其格式。WWW-Authenticate - 开销。 按默认 cost 计算,一次 hash 约需 0.3 s 和 128 MiB 内存,并占用 libuv threadpool。测试中可覆盖配置:。应对登录接口进行限流(
.overrideProvider(PasswordHasher).useValue(new PasswordHasher({ logN: 10 })))。nestjs-production - 内存存储。 在注册 store 之前,session 和 refresh token 一直保存在内存中;使用 时,模块会拒绝以此方式启动。仅使用 Bearer token 的 API 可以关闭 refresh token:
NODE_ENV=production。refreshToken: false
Pick the setup
选择配置方式
| The app needs | Use |
|---|---|
| Bearer JWTs it issues itself, secret up to you | |
| A secret or token format fixed by the task | |
| Browser sessions | |
| Keys for scripts and partners | |
| Roles or ownership checks | |
Code for each row, checked against 0.1.6 and 0.1.4: references/authentication.md, references/authorization.md.
@nestjs/authentication@nestjs/authorization| 应用需求 | 使用方式 |
|---|---|
| 自行签发 Bearer JWT,secret 可自行决定 | |
| 任务指定了固定的 secret 或 token 格式 | |
| 浏览器 session | |
| 用于脚本和合作伙伴的 key | |
| Role 或所有权检查 | |
每种方式的代码均已针对 0.1.6 和 0.1.4 进行核对:references/authentication.md、references/authorization.md。
@nestjs/authentication@nestjs/authorization