nestjs-auth

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Authentication and authorization in NestJS

NestJS 中的 authentication 与 authorization

Use the first-party packages rather than assembling auth from
@nestjs/jwt
, Passport and bcrypt:
bash
npm i @nestjs/authentication @nestjs/authorization
  • @nestjs/authentication
    (docs: https://docs.nestjs.com/security/authentication.md): a global guard that puts every route behind sign-in,
    @Public()
    to open one,
    @Authenticate({ optional: true })
    ,
    @CurrentUser()
    ,
    PasswordHasher
    (scrypt), sessions,
    TokenService
    (JWT access + rotating refresh tokens),
    ApiKeyProvider
    , TOTP, magic links, OIDC. No third-party dependencies.
  • @nestjs/authorization
    (docs: https://docs.nestjs.com/security/authorization.md): policies as providers,
    @Can(Policy, 'ability')
    on routes,
    AuthorizationService.authorize()
    in services. Denies a route that declares no check.
使用第一方包,而不是通过
@nestjs/jwt
、Passport 和 bcrypt 自行拼装 auth:
bash
npm i @nestjs/authentication @nestjs/authorization
  • @nestjs/authentication
    (文档:https://docs.nestjs.com/security/authentication.md):提供一个全局 guard,将所有路由置于登录保护之下;使用
    @Public()
    开放特定路由;支持
    @Authenticate({ optional: true })
    、
    @CurrentUser()
    、
    PasswordHasher
    (scrypt)、session、
    TokenService
    (JWT access token + 轮换的 refresh token)、
    ApiKeyProvider
    、TOTP、magic link 和 OIDC。无第三方依赖。
  • @nestjs/authorization
    (文档:https://docs.nestjs.com/security/authorization.md):将 policy 作为 provider,在路由上使用
    @Can(Policy, 'ability')
    ,也可在 service 中使用
    AuthorizationService.authorize()
    。对于未声明任何检查项的路由,默认拒绝访问。

Rules that matter

重要规则

  • Check passwords with
    PasswordHasher.verify(password, found?.passwordHash)
    , and only then decide. With no user it checks a dummy hash, so an unknown email takes as long as a wrong password. Never
    if (!user) throw
    before the hash check: the faster answer tells anyone which emails are registered. Hash with
    passwordHasher.hash()
    ; inject
    PasswordHasher
    (the module provides it).
  • Sign-in is
    @Post()
    +
    @HttpCode(200)
    : it creates nothing, so not 201.
  • accessToken.key
    must be at least 32 bytes
    for HS256 (
    openssl rand -base64 32
    ); 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.
  • When the task fixes the secret or the token format (a given
    JWT_SECRET
    , a default value, tokens other services verify), keep it exactly. If it's under 32 bytes, sign and verify with
    @nestjs/jwt
    using that secret, and plug verification into
    @nestjs/authentication
    as your own
    AuthenticationProvider
    , so the global guard,
    @Public()
    and
    @CurrentUser()
    still work. Say in your summary that the secret is too short for production. Code: references/authentication.md.
  • Refresh tokens rotate and detect theft.
    TokenService.refresh()
    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
    ttl
    short.
  • Services read the user from
    AuthenticationContext
    (
    requireUser()
    ), a singleton backed by
    AsyncLocalStorage
    : no request-scoped providers, and
    run({ user }, fn)
    for workers and tests.
  • Load the user on every request in the provider's
    validate()
    /
    authenticate()
    , and read roles from it, not from token claims: a role change or a deleted user then takes effect at once.
  • Global guards run in import order: import
    AuthenticationModule
    before
    AuthorizationModule
    (the app refuses to start otherwise). A custom guard that sets
    request.user
    goes in as
    APP_GUARD
    before
    AuthorizationModule
    .
  • @nestjs/authorization
    denies every route that declares nothing
    : once
    AuthorizationModule
    is imported, a signed-in user gets 403 on any handler without
    @Can()
    ,
    @Can.Anyone()
    or
    @Public()
    (the startup log lists them). Adding it to an existing app, put
    @Can.Anyone()
    on routes any signed-in user may call (e.g.
    GET /me
    , the user's own resources) and re-test them.
  • 401 vs 403: no or bad credentials is 401 (the guard's), signed in but not allowed is 403 (
    @Can()
    or
    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:
    takeUntil()
    on a revocation signal, shown in
    nestjs-feature
    's
    references/http.md
    .
  • Response bodies. The guard's 401 is an
    HttpException
    (
    { statusCode, message, errorCode }
    plus a
    WWW-Authenticate
    header): a global exception filter can reshape it like any other error.
  • Cost. At its default cost a hash takes ~0.3 s and 128 MiB, on the libuv threadpool. Tests override it:
    .overrideProvider(PasswordHasher).useValue(new PasswordHasher({ logN: 10 }))
    . Throttle sign-in (
    nestjs-production
    ).
  • In-memory stores. Sessions and refresh tokens live in memory until you register a store, and with
    NODE_ENV=production
    the module refuses to start that way. A bearer-only API can turn refresh tokens off:
    refreshToken: false
    .
  • 使用
    PasswordHasher.verify(password, found?.passwordHash)
    校验密码
    ,并且仅在此之后作出判断。如果用户不存在,它会校验一个虚拟 hash,因此未知 email 所耗费的 time 与错误密码相同。绝不要在 hash 校验之前执行
    if (!user) throw
    :更快的响应会泄露哪些 email 已注册。使用
    passwordHasher.hash()
    生成 hash;注入
    PasswordHasher
    (模块会提供它)。
  • 登录接口使用
    @Post()
    +
    @HttpCode(200)
    :该接口不会创建资源,因此不应返回 201。
  • 对于 HS256,
    accessToken.key
    必须至少为 32 bytes
    (
    openssl rand -base64 32
    );密钥过短会导致应用在启动时停止。绝不要对短 secret 进行 hash、补位或派生更长密钥:这样生成的 token 会使用不同的密钥签名,而任何使用配置的 secret 校验 token 的服务都会拒绝这些 token。
  • 当任务要求修复 secret 或 token 格式时(指定
    JWT_SECRET
    、默认值,或其他服务需要校验的 token),必须完全保持其格式。如果 secret 不足 32 bytes,请使用
    @nestjs/jwt
    和该 secret 进行签名与校验,并将其作为自定义
    AuthenticationProvider
    接入
    @nestjs/authentication
    ,以确保全局 guard、
    @Public()
    和
    @CurrentUser()
    仍然正常工作。在总结中说明该 secret 对于 production 环境而言过短。代码:references/authentication.md。
  • Refresh token 会轮换并检测盗用。
    TokenService.refresh()
    会消费每个 refresh token;重复使用同一个 token 会返回 401,并撤销其整个 token family,因此客户端必须重新登录。Access token 在过期前始终有效:应保持
    ttl
    较短。
  • Service 从
    AuthenticationContext
    (
    requireUser()
    )读取用户
    。它是一个基于
    AsyncLocalStorage
    的单例:无需使用 request-scoped provider;对于 worker 和测试,使用
    run({ user }, fn)
    。
  • 在每个请求中加载用户,在 provider 的
    validate()
    /
    authenticate()
    中完成,并从用户信息而非 token claims 中读取 roles:这样角色变更或用户删除后可以立即生效。
  • 全局 guard 按 import 顺序执行:先 import
    AuthenticationModule
    ,再 import
    AuthorizationModule
    (否则应用会拒绝启动)。用于设置
    request.user
    的自定义 guard 应通过
    APP_GUARD
    注册,并位于
    AuthorizationModule
    之前。
  • @nestjs/authorization
    会拒绝所有未声明检查项的路由
    :一旦 import
    AuthorizationModule
    ,已登录用户访问没有
    @Can()
    、
    @Can.Anyone()
    或
    @Public()
    标记的 handler 时都会收到 403(启动日志会列出这些路由)。将其接入已有应用时,应为任何已登录用户均可调用的路由添加
    @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 }
    ,并附带
    WWW-Authenticate
    header):全局 exception filter 可以像处理其他错误一样重新设置其格式。
  • 开销。 按默认 cost 计算,一次 hash 约需 0.3 s 和 128 MiB 内存,并占用 libuv threadpool。测试中可覆盖配置:
    .overrideProvider(PasswordHasher).useValue(new PasswordHasher({ logN: 10 }))
    。应对登录接口进行限流(
    nestjs-production
    )。
  • 内存存储。 在注册 store 之前,session 和 refresh token 一直保存在内存中;使用
    NODE_ENV=production
    时,模块会拒绝以此方式启动。仅使用 Bearer token 的 API 可以关闭 refresh token:
    refreshToken: false
    。

Pick the setup

选择配置方式

The app needsUse
Bearer JWTs it issues itself, secret up to you
accessToken
options +
JwtBearerProvider
+
TokenService.issue()
A secret or token format fixed by the task
@nestjs/jwt
+ your own
AuthenticationProvider
Browser sessions
SessionCookieProvider
+
SignInService.signIn()
Keys for scripts and partners
ApiKeyProvider
(keys
prefix_<id>_<secret>
, stored as SHA-256) or your own provider for another header; manage keys only from a session (
@Authenticate({ providers: [SessionAuth] })
), so a leaked key can't mint more
Roles or ownership checks
@nestjs/authorization
policies
Code for each row, checked against
@nestjs/authentication
0.1.6 and
@nestjs/authorization
0.1.4: references/authentication.md, references/authorization.md.
应用需求使用方式
自行签发 Bearer JWT,secret 可自行决定
accessToken
options +
JwtBearerProvider
+
TokenService.issue()
任务指定了固定的 secret 或 token 格式
@nestjs/jwt
+ 自定义
AuthenticationProvider
浏览器 session
SessionCookieProvider
+
SignInService.signIn()
用于脚本和合作伙伴的 key
ApiKeyProvider
(key 格式为
prefix_<id>_<secret>
,使用 SHA-256 存储),或为其他 header 实现自定义 provider;只能通过 session 管理 key(
@Authenticate({ providers: [SessionAuth] })
),防止泄露的 key 继续创建更多 key
Role 或所有权检查
@nestjs/authorization
policy
每种方式的代码均已针对
@nestjs/authentication
0.1.6 和
@nestjs/authorization
0.1.4 进行核对:references/authentication.md、references/authorization.md。