nestjs-auth
Skill12 starsChanged 8 days agoMITView on GitHub
Sign-in, sessions, bearer tokens, API keys and permissions in a NestJS application with the first-party @nestjs/authentication and @nestjs/authorization packages - timing-safe password checks, a global guard with @Public(), policies with @Can(), and what to do when a task fixes the JWT secret or token format. Use when adding or changing authentication or authorization in a NestJS application.
- Installs packages
1 other project uses a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- nestjs/typescript-starteredited, first seen Nov 30, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 1
- nestjs/typescript-starter★ 2.2k100% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository41 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .claude/skills/react-doctor/AGENTS.mdAGENTS.md
- .claude/skills/vercel-react-best-practices/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- ai-agent-developmentSkill
- angular-developerSkill
- api-design-principlesSkill
- aws-serverlessSkill
- brainstormingSkill
- cavemanSkill
- cognitive-doc-designSkill
- diagram-designSkill
- error-handling-patternsSkill
- frontend-designSkill
- golang-proSkill
- gsap-animationSkill
- impeccable-bridgeSkill
- impeccableSkill
- java-springbootSkill
- judgment-daySkill
- kaizenSkill
- nestjs-dataSkill
- nestjs-featureSkill
- nestjs-productionSkill
- nestjsSkill
- nestjs-testingSkill
- product-manager-toolkitSkill
- pr-reviewSkill
- react-doctorSkill
- security-auditSkill
- seo-auditSkill
- shadcn-uiSkill
- social-marketingSkill
- software-architectSkill
- stitch-designSkill
- systematic-debuggingSkill
- tailwind-design-systemSkill
- tddSkill
- ui-ux-pro-maxSkill
- vercel-react-best-practicesSkill
- video-productionSkill
The file
We split this skill into the rules it gives an agent
3 rules. About 0 are common, 0 are distinctive, and 3 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
3
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 15
Use the first-party packages rather than assembling auth from @nestjs/jwt, Passport and bcrypt:
- Very specific: line 33
Global guards run in import order: import AuthenticationModule before AuthorizationModule (the app refuses to start otherwise).
- Very specific: line 35
401 vs 403: no or bad credentials is 401 (the guard's), signed in but not allowed is 403 (@Can() or ForbiddenException).
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Authentication and authorization in NestJS
Use the first-party packages rather than assembling auth from @nestjs/jwt, Passport and bcrypt:
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.
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. Neverif (!user) throwbefore the hash check: the faster answer tells anyone which emails are registered. Hash withpasswordHasher.hash(); injectPasswordHasher(the module provides it). - Sign-in is
@Post()+@HttpCode(200): it creates nothing, so not 201. accessToken.keymust 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/jwtusing that secret, and plug verification into@nestjs/authenticationas your ownAuthenticationProvider, 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: keepttlshort. - Services read the user from
AuthenticationContext(requireUser()), a singleton backed byAsyncLocalStorage: no request-scoped providers, andrun({ 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
AuthenticationModulebeforeAuthorizationModule(the app refuses to start otherwise). A custom guard that setsrequest.usergoes in asAPP_GUARDbeforeAuthorizationModule. @nestjs/authorizationdenies every route that declares nothing: onceAuthorizationModuleis 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()orForbiddenException). - 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 innestjs-feature'sreferences/http.md. - Response bodies. The guard's 401 is an
HttpException({ statusCode, message, errorCode }plus aWWW-Authenticateheader): 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=productionthe module refuses to start that way. A bearer-only API can turn refresh tokens off:refreshToken: false.
Pick the setup
| The app needs | Use |
| 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.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

