Authentication is one of those topics that seems like it would be simple. A user submits a username and password, the server verifies the credentials, and the application returns a token.
But a secure authentication system involves more than just generating a JSON Web Token (JWT). You also need to think about password storage, access and refresh tokens, token rotation, session management, logout, concurrent requests, authorization, CSRF protection, rate limiting, input validation, CORS, secure cookies, database consistency, security monitoring, and...the list goes on.
In this handbook, we'll examine an authentication and authorization architecture for a full-stack application built with Angular, NestJS, MongoDB, and Redis. Our goals here are to understand the responsibilities of each component, how they work together, and which additional controls we need to verify before deploying a real application.
The design uses a short-lived access JWT held in Angular memory and an opaque refresh token delivered through an HttpOnly cookie. The backend stores a hash of the refresh token in MongoDB, uses session records to track logins, and uses Redis for rate limiting and other temporary state. The server (not the Angular UI) remains the security boundary for authentication and authorization.
Table of Contents
- Prerequisites
- 1. Authentication vs Authorization
- 2. The Architecture
- 3. What We Will Build
- 4. Why Not Store Everything in localStorage?
- 5. Project Structure
- 6. Install Dependencies
- 7. Environment Configuration
- 8. User Model
- 9. Password Hashing
- 10. Registration
- 11. Sessions
- 12. Refresh Tokens
- 13. Access JWT
- 14. Login
- 15. Angular AuthService
- 16. Handling Expired Access Tokens
- 17. Refresh Token Rotation
- 18. Why We Have Sessions
- 19. JWT Authentication in NestJS
- 20. RBAC
- 21. CSRF
- 22. Redis
- 23. CORS
- 24. Logout
- 25. MongoDB Transaction for Rotation
- 26. Complete Authentication Flow
- 27. Security Review
- 28. Things We Should Add Later
- 29. The Most Important Architectural Lessons
- 30. Final Architecture
- Explore the Source Code
Prerequisites
This tutorial will be approachable for you if you already know the basics of JavaScript and TypeScript and have built a small application with Angular or another frontend framework. Familiarity with HTTP requests, REST APIs, and basic database operations will make the examples easier to follow. You don't need to be a security specialist, but you should be comfortable reading backend TypeScript.
You'll also need Node.js and npm, the Angular CLI, a NestJS project, MongoDB, Redis, and a tool for sending HTTP requests such as Postman or curl. Git and an editor such as VS Code are also useful. You can run MongoDB and Redis locally or use managed development instances.
The snippets below illustrate the important parts of the design. But they're not a substitute for checking the complete repository, configuring every endpoint, and running automated security tests. Package versions and some bootstrap details can differ between project versions.
1. Authentication vs Authorization
Before we start, you need to know the difference between these two terms.
Authentication answers the question, “Who are you?” The server verifies the credentials or validates an existing session and establishes the identity associated with the request.
For example, a user submits an email address and password. If the credentials are valid, the server identifies the corresponding user. The client shouldn't be allowed to choose or forge that identity.
Authorization answers a different question: “What is this authenticated user allowed to do?” A user with an ADMIN role might be allowed to manage accounts, while a regular USER might be allowed to view or update only their own profile.
Authentication must happen before protected authorization rules can be evaluated. But a role check alone isn't always enough: an endpoint that reads /orders/123 must also verify that the current user is allowed to access that particular order. We'll return to this distinction when we discuss RBAC and resource ownership below.
2. The Architecture
The browser runs the Angular application, while NestJS exposes the API and makes security decisions. MongoDB stores durable user, session, and refresh-token records. Redis supports rate limiting and other temporary or shared state that shouldn't depend on one API process.
Angular │ ┌─────────┴─────────┐ │ │ Access Token Refresh Cookie │ │ ▼ ▼ Authorization Header HttpOnly │ │ └─────────┬─────────┘ ▼ NestJS │ ┌────────┴────────┐ │ │ Authentication Authorization │ │ JWT Strategy RolesGuard │ │ └────────┬────────┘ │ ▼ Service │ ┌────────┴────────┐ ▼ ▼ MongoDB Redis │ │ Users/Sessions Rate Limits Refresh Tokens Temporary State We'll use a hybrid authentication model. The access token is a short-lived JWT that Angular keeps in memory and sends in the Authorization header. The refresh token is a cryptographically random, opaque value (not another JWT) and is sent by the browser in an HttpOnly cookie. MongoDB stores only a hash of that refresh token, along with its session and lifecycle metadata.
This is a deliberate division of responsibilities: the access token lets the API authenticate ordinary requests, while the refresh token lets the server continue a session after the access token expires. Because refresh tokens are tracked server-side, they can be rotated and revoked. A signed JWT isn't automatically revocable, though. If immediate access-token revocation is required, the API must also check session status or use another revocation strategy on protected requests.
3. What We Will Build
Before discussing browser storage, let's establish the scope. The example architecture covers account registration, password hashing, login, short-lived access JWTs, opaque refresh tokens, refresh-token rotation and reuse detection, per-device sessions, logout, role-based access control, request validation, CSRF considerations, CORS, and rate limiting with Redis.
The Angular side keeps the access token in memory, adds it to protected API requests, and coordinates refresh attempts when requests fail because a token has expired. The NestJS side validates credentials and tokens, enforces permissions, and updates server-side session state. MongoDB stores durable identity and session records, while we use Redis for rate-limit state and other temporary coordination where configured.
This is a learning architecture, not a guarantee that every deployment is production-ready. You should implement and verify email verification, password reset, multi-factor authentication, robust audit logging, monitoring, deployment-specific cookie settings, cross-tab refresh coordination, and a complete automated security test suite for any real application's needs.
4. Why Not Store Everything in localStorage?
A common implementation stores an access token in localStorage because it survives page reloads. The trade-off is that any JavaScript executing in the origin can read it. If an attacker exploits a cross-site scripting (XSS) vulnerability, injected JavaScript may read the token and send it to an external server. The same XSS can often perform actions as the user even if the token is kept only in memory, so in-memory storage reduces persistence and straightforward extraction but doesn't eliminate XSS risk.
In this design, Angular keeps the short-lived access token in memory. The refresh token is stored in an HttpOnly cookie, which prevents ordinary page JavaScript from reading its value. This makes direct refresh-token extraction through document.cookie harder, but it doesn't make XSS harmless. It also doesn't, by itself, prevent cross-site request forgery (CSRF). Cookie-based refresh endpoints still need an intentional SameSite policy and appropriate CSRF/origin defenses.
Angular Memory ↓ Access Token HttpOnly Cookie ↓ Refresh Token JavaScript can't directly read an HttpOnly cookie, but the browser can still attach it to matching requests. That's why cookie configuration and CSRF defenses are important.
5. Project Structure
The following are two parts of the same full-stack application, not mutually exclusive alternatives. The NestJS tree belongs to the backend API, while the Angular tree belongs to the browser client. They can live in separate repositories or under separate apps/api and apps/web folders in a monorepo.
Choose the arrangement that fits your team's deployment and tooling. Don't combine the two src trees into one application directory.
The backend separates authentication endpoints and token logic from user data, session persistence, and Redis integration. Guards and decorators provide reusable request-level security rules. In a larger system, some of these responsibilities might be split into additional modules.
Here's a possible NestJS structure:
src/ ├── auth/ │ ├── auth.controller.ts │ ├── auth.service.ts │ ├── auth.module.ts │ ├── token.service.ts │ ├── strategies/ │ │ └── jwt.strategy.ts │ ├── guards/ │ │ ├── jwt-auth.guard.ts │ │ ├── roles.guard.ts │ │ └── csrf.guard.ts │ └── decorators/ │ ├── public.decorator.ts │ ├── roles.decorator.ts │ └── current-user.decorator.ts │ ├── users/ │ ├── users.service.ts │ ├── users.module.ts │ └── schemas/ │ └── user.schema.ts │ ├── sessions/ │ ├── sessions.service.ts │ ├── sessions.module.ts │ └── schemas/ │ ├── session.schema.ts │ └── refresh-token.schema.ts │ ├── redis/ │ ├── redis.service.ts │ └── redis.module.ts │ └── app.module.ts The Angular structure is the client-side counterpart. AuthService manages authentication requests and the in-memory access token. Interceptors attach the access token and handle CSRF-related headers where appropriate. The guard improves the navigation experience, but doesn't replace backend authorization. auth.types.ts contains client-side request/response types, and auth.store.ts can expose authentication state to components. Avoid storing the refresh token in Angular state. The browser manages the HttpOnly cookie.
Angular:
src/app/core/auth/ ├── auth.service.ts ├── auth.interceptor.ts ├── csrf.interceptor.ts ├── auth.guard.ts ├── auth.types.ts └── auth.store.ts 6. Install Dependencies
Run the following in the NestJS backend project. These packages provide configuration, MongoDB integration, JWT and Passport authentication, password hashing, cookie parsing, DTO validation, and Redis access. If your repository already includes some packages, check package.json before installing duplicates.
For NestJS:
npm install \ @nestjs/config \ @nestjs/mongoose \ @nestjs/jwt \ @nestjs/passport \ passport \ passport-jwt \ mongoose \ bcrypt \ cookie-parser \ class-validator \ class-transformer \ ioredis Here's what the runtime dependencies do:
@nestjs/configloads environment configuration and exposes it throughConfigService.@nestjs/mongooseintegrates Mongoose models with NestJS.mongoosedefines schemas and communicates with MongoDB.@nestjs/jwtsigns and verifies JWTs.@nestjs/passport,passport, andpassport-jwtconnect Passport strategies to NestJS authentication flows.bcrypthashes passwords and compares login attempts against stored password hashes.cookie-parserparses the incomingCookieheader so Express requests can expose parsed cookies. Register its middleware in the application bootstrap if your setup requires it.class-validatorandclass-transformersupport DTO validation and transformation when used with NestJS'sValidationPipe.ioredisis a Redis client used for rate-limit counters and other shared temporary state.
The -D flag installs development dependencies. The @types/* packages provide TypeScript declarations for libraries that don't ship all the needed types. They help the compiler and editor and aren't application runtime services. Exact type packages depend on the versions and TypeScript setup used by your project.
Development types:
npm install -D \ @types/bcrypt \ @types/cookie-parser \ @types/passport-jwt 7. Environment Configuration
Create a local .env file for development and load it through NestJS configuration. These values are illustrative local settings, not production secrets.
Never commit a real .env file. Commit an .env.example containing only safe placeholder values instead. In production, generate a high-entropy secret and provide it through your hosting platform's secret manager or protected environment configuration.
Validate required variables when the application starts so a missing or malformed secret doesn't remain unnoticed until a request arrives. Also, keep the configuration and implementation consistent: if ACCESS_TOKEN_EXPIRES_IN is configurable, the token service should read that variable instead of hard-coding '15m' in the signing call.
PORT=3000 MONGO_URI=mongodb://localhost:27017/secure_auth REDIS_HOST=localhost REDIS_PORT=6379 JWT_ACCESS_SECRET=strong-random-secret ACCESS_TOKEN_EXPIRES_IN=15m NODE_ENV=development MONGO_URI points to the MongoDB database, and the Redis host and port tell the application where to connect for rate limiting. JWT_ACCESS_SECRET signs access tokens, so it must be unpredictable and protected. ACCESS_TOKEN_EXPIRES_IN documents the intended short lifetime. Make sure the implementation actually reads it. NODE_ENV controls environment-specific settings such as whether cookies use the Secure attribute.
Notice that we don't need a JWT_REFRESH_SECRET variable because the refresh token isn't a JWT. It's a random opaque token.
8. User Model
Before we can register users or authenticate them, we need somewhere to store the information that identifies each account. In this application, the User model represents one registered person. It holds the details we need during authentication, such as the email address and password hash, as well as account information like the user's name, email-verification status, and role.
We'll start by defining the roles the application understands:
export enum UserRole { USER = 'user', ADMIN = 'admin', MODERATOR = 'moderator', } An enum gives us a fixed set of role values instead of scattering strings such as 'admin' and 'user' throughout the code. That makes role checks easier to keep consistent. These values describe permissions assigned by the application. They aren't values a person should be able to choose freely during public registration.
Next, we can define the Mongoose schema for a user:
@Schema({ timestamps: true }) export class User { @Prop({ required: true, unique: true, lowercase: true, trim: true, }) email: string; @Prop({ required: true, }) passwordHash: string; @Prop({ required: true, trim: true, }) name: string; @Prop({ default: false, }) emailVerified: boolean; @Prop({ type: String, enum: Object.values(UserRole), default: UserRole.USER, }) role: UserRole; } export const UserSchema = SchemaFactory.createForClass(User); Each @Prop() decorator tells Mongoose how a field should be stored and validated. For example, the email is required and normalized to lowercase with surrounding whitespace removed. The unique option asks MongoDB to create a unique index so two accounts can't share the same email address. We'll discuss why we still need to handle duplicate-key errors in the "Database Constraints Are Still Required" subsection of the Registration section.
The passwordHash field stores the result of password hashing, not the original password. name is required, emailVerified starts as false, and role defaults to USER. The SchemaFactory call turns the decorated class into the Mongoose schema used to create the model.
Notice that the model has no plain password field. We only keep passwordHash, because the original password should never be recoverable from the database.
9. Password Hashing
Password hashing protects users if someone gains access to the database. Instead of saving the password itself, the server saves a one-way hash. During login, it checks a newly submitted password against that hash. The application should never log a password or include one in an API response.
Human passwords are usually much easier to guess than randomly generated secrets. People tend to choose familiar words, names, dates, or patterns, and attackers can try large lists of likely passwords. In security terms, this means passwords often have relatively low entropy: there may be fewer plausible combinations than the password's length alone suggests.
That's why we shouldn't use a fast general-purpose hash such as plain SHA-256 for passwords. An attacker with a stolen password database could test guesses very quickly.
Password-hashing algorithms such as bcrypt and Argon2 are deliberately expensive: they make each guess take more time and computational resources. They also use a salt, so identical passwords don't produce identical stored hashes. This doesn't make weak passwords impossible to crack, but it makes large-scale guessing much more costly.
For this example, we'll use bcrypt with a cost factor of 12:
const passwordHash = await bcrypt.hash( password, 12, ); When the user logs in, we don't hash the submitted password ourselves and compare two strings. Bcrypt stores the salt and cost information as part of the encoded hash, and compare() uses that information to run the appropriate verification process:
const valid = await bcrypt.compare( password, user.passwordHash, ); A direct comparison such as password === passwordHash won't work because the submitted password is plain text while passwordHash is a salted, encoded hash. They're different values, and a secure password hash isn't designed to be reversed. Use bcrypt.compare() so the library can verify the password using the salt and parameters stored in the hash.
Also, don't use encryption as a substitute for password hashing. Encryption is designed to be reversible when you have the key, and an application shouldn't need to decrypt a user's password at all. Store a password hash and verify it when the user signs in.
10. Registration
Registration is the first place where data from an unknown client enters our application. We shouldn't pass that data straight into a database operation. First, we need to check that the request contains the fields we expect and that those fields have sensible values. Then we should explicitly map the accepted values into the user record.
In NestJS, a Data Transfer Object (DTO) describes the shape of data that an endpoint accepts or returns. For registration, the DTO is the contract for the request body. We can use decorators from class-validator to describe rules such as “this value must be an email address” or “the password must be between 8 and 128 characters.” NestJS's ValidationPipe runs those checks before the controller handles the request.
Here's a registration DTO:
export class RegisterDto { @IsEmail() email: string; @IsString() @MinLength(8) @MaxLength(128) password: string; @IsString() @MinLength(2) @MaxLength(100) name: string; } Enable validation globally:
app.useGlobalPipes( new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true, }), ); This is important because an attacker might send:
{ "email": "user@example.com", "password": "password", "role": "admin" } Notice that role isn't part of RegisterDto. That's intentional. A public registration endpoint should let someone provide their email, password, and name, but it shouldn't let them decide whether they're a regular user, moderator, or administrator. The user model supplies the default role (USER) on the server.
Because we enabled whitelist and forbidNonWhitelisted, NestJS rejects a request that includes a property that isn't declared in the DTO. For example, a request that tries to add "role": "admin" will fail validation instead of silently passing that property through. The controller should still create the user from an explicit list of accepted fields rather than spreading the entire request object into a database document.
The request therefore follows this path:
Client sends registration data ↓ ValidationPipe checks the DTO ↓ Known, valid fields reach the controller ↓ Controller/service maps allowed fields ↓ User is created with the server-side default role This is one way to reduce the risk of mass assignment: accidentally allowing a client to set internal fields that should only be controlled by the server.
Database Constraints Are Still Required
It's useful to check whether an email address is already registered before trying to create an account. That lets the API return a friendly response in the common case. But this application-level check is only a convenience. It can't guarantee uniqueness when requests arrive at the same time.
For example, two registration requests can both check the database before either one has inserted its new user. Both checks may report that the email is available, and then both requests may try to create an account. A unique index in MongoDB is what prevents the duplicate record from being saved.
You can still perform an early lookup:
const existing = await usersService.findByEmail(email); But this isn't enough.
Two requests can arrive simultaneously:
Request A → email doesn't exist Request B → email doesn't exist And both may attempt to create the account.
So the schema needs a unique index on the email field:
unique: true The database index handles the race condition. If both requests pass the earlier lookup, MongoDB allows the first insert and rejects the second with a duplicate-key error (usually error code 11000).
The registration service is the part of the application that should catch that database error. It can translate the database-specific error into a predictable HTTP response, such as 409 Conflict, without exposing raw MongoDB details to the client. For example:
try { return await this.usersService.create({ email, passwordHash, name, }); } catch (error) { if ( error && typeof error === 'object' && 'code' in error && error.code === 11000 ) { throw new ConflictException( 'An account with this email already exists', ); } throw error; } This is illustrative: put the try/catch around the operation that actually performs the insert, whether that lives in AuthService or UsersService in your project. The important part is that the layer handling account creation translates the duplicate-key error, while unexpected database errors continue to be handled by the application's regular error handling.
The early lookup improves the user experience, the unique index guarantees the data constraint, and the service turns a database error into a safe API response. Each has a different job.
11. Sessions
A session represents one authenticated login context, such as a browser on a laptop or a phone. Keeping session state separately from the user record makes it possible to track devices, last activity, expiry, and revocation.
It's worth keeping these concepts separate: a user is the account, while a session represents one active login for that account. One user can sign in from several devices or browsers at the same time. For example, the same account might have sessions for:
Laptop Phone Tablet For that reason, the request should follow this path:
User ├── Session A ├── Session B └── Session C A Session can contain:
@Schema({ timestamps: true }) export class Session { @Prop({ required: true, index: true }) userId: Types.ObjectId; @Prop({ required: true, unique: true, index: true, }) sessionId: string; @Prop({ required: true }) expiresAt: Date; @Prop({ default: null }) revokedAt: Date | null; @Prop() ip?: string; @Prop() userAgent?: string; @Prop() lastUsedAt?: Date; } This gives us a place to track sessions, but the application must actually consult and update these records in its authentication flow. If protected requests validate only the JWT signature and expiration, revoking a session won't immediately invalidate an already-issued access token.
For immediate revocation, the JWT strategy must also validate the session ID (sid) against current server-side session state, or the system must use another revocation mechanism. This check has a performance and availability cost that you should consider explicitly.
12. Refresh Tokens
Refresh tokens are long-lived credentials, so their lifecycle needs more protection than a short-lived access token. A separate collection makes it possible to revoke and audit each token in a rotation chain.
Instead of storing one refresh token directly inside the Session document, we can create a dedicated collection.
@Schema({ timestamps: true }) export class RefreshToken { @Prop({ required: true, index: true, type: Types.ObjectId, ref: 'User', }) userId: Types.ObjectId; @Prop({ required: true, index: true, }) sessionId: string; @Prop({ required: true, unique: true, index: true, }) tokenHash: string; @Prop({ required: true, unique: true, index: true, }) tokenId: string; @Prop({ required: true }) expiresAt: Date; @Prop({ default: null }) revokedAt: Date | null; @Prop({ default: null }) replacedBy: string | null; @Prop() usedAt?: Date; @Prop() ip?: string; @Prop() userAgent?: string; } Why keep refresh tokens in a separate collection instead of storing a single token on the session? Because every successful rotation replaces the current token, and we want to retain enough history to recognize an older token if it appears again. That history forms a chain:
R1 → R2 → R3 → R4 We want to be able to track that history.
Generating Refresh Tokens
You can generate refresh tokens with a cryptographically secure random-number generator. Don't use timestamps, ordinary pseudo-random values, or user-controlled strings as authentication secrets.
A refresh token doesn't need to be a JWT. Since the server already stores and checks its state, a cryptographically random opaque string is enough.
We can generate one with Node.js's crypto module like this:
import { randomBytes } from 'crypto'; const refreshToken = randomBytes(32).toString('hex'); This produces a high-entropy random secret.
We also need two identifiers that tie the records together. We can create them the same way:
const sessionId = randomBytes(16).toString('hex'); const tokenId = randomBytes(16).toString('hex'); These two values play different roles from the refresh token itself:
sessionIdidentifies one login (one device or browser). Every refresh token created for that login stores the samesessionId, which is how the server knows which tokens belong together and can revoke them all at once. It's also the value that ends up in thesidclaim of the access JWT.tokenIdis a unique label for one specific refresh-token record. During rotation, the old record'sreplacedByfield points to the new record'stokenId, which is how we build the chainR1 → R2 → R3.
Neither one is the secret that the browser sends back. The secret is refreshToken. We still generate the identifiers randomly so they're unique and hard to guess.
Hashing the Refresh Token
You'll want to store a hash rather than the raw refresh token so a database read alone doesn't reveal a directly reusable credential. Since the token is random and high-entropy, a fast cryptographic hash is suitable for lookup. This differs from human passwords, which need slow password hashing.
The browser needs the raw refresh token so it can send it back later, but the database does not. If someone reads the database, a stored hash is much less useful to them than a directly reusable token. Here, we'll hash the token before saving it:
import { createHash } from 'crypto'; export function hashToken( token: string, ): string { return createHash('sha256') .update(token) .digest('hex'); } The flow becomes:
Raw Refresh Token ↓ SHA-256 ↓ MongoDB Why SHA-256 instead of bcrypt?
Because the refresh token is random and high-entropy, unlike a human password. A fast cryptographic hash is appropriate for this kind of server-side lookup.
13. Access JWT
A JWT is signed, not encrypted by default. Its signature helps the API detect changes, but anyone who obtains the token can usually decode its payload. For that reason, it's best to keep the payload small and include only the claims the API needs. Never put passwords, secrets, or unnecessary personal information in it.
For this design, the access token needs three claims:
{ sub: userId, sid: sessionId, type: 'access' } submeans subject, usually the user ID.sidmeans Session IDtypeprevents accidentally using another token type as an access token.
Creating the Access Token
It's best to keep the signing secret outside source control and validate it during startup. Your token verification strategy should use compatible algorithm and claim expectations. Don't accept an algorithm merely because it appears in an incoming token.
async createAccessToken(data: { userId: string; sessionId: string; }) { return this.jwtService.signAsync( { sub: data.userId, sid: data.sessionId, type: 'access', }, { secret: this.configService.getOrThrow<string>( 'JWT_ACCESS_SECRET', ), expiresIn: this.configService.getOrThrow<string>( 'ACCESS_TOKEN_EXPIRES_IN', ), }, ); } The short expiration is intentional. The configured lifetime should match the value used by the signing code, and the JWT strategy should validate the expected algorithm, signature, expiration, and token type. If the API also checks session revocation, it should validate the sid claim against the active session record.
If an access token is stolen, make sure that token has a limited lifetime. A short TTL reduces the damage window.
14. Login
Now that we have users, sessions, refresh tokens, and access tokens, we can put them together in the login endpoint. In this section, we'll look at the overall flow first, then the implementation, and then why the refresh token is delivered in an HttpOnly cookie.
The Login Flow
Here's the complete conceptual flow to help you visualize how everything's working:
POST /auth/login │ ▼ Find user │ ▼ Compare password │ ▼ Create Session │ ├── sessionId │ ▼ Create Refresh Token │ ├── random secret ├── hash └── store hash │ ▼ Create Access JWT │ ▼ Set HttpOnly Cookie │ ▼ Return accessToken Login Implementation
This example shows the main steps, but a complete implementation should also validate the DTO, apply rate limits, handle database failures, and ensure the session and refresh-token records are created consistently. Don't reveal whether the email or password was wrong. Instead, use a generic credential error.
async login( dto: LoginDto, req: Request, res: Response, ) { const email = dto.email.trim().toLowerCase(); const user = await this.usersService.findByEmail(email); if (!user) { throw new UnauthorizedException( 'Invalid credentials', ); } const valid = await bcrypt.compare( dto.password, user.passwordHash, ); if (!valid) { throw new UnauthorizedException( 'Invalid credentials', ); } const sessionId = randomBytes(16).toString('hex'); const refreshToken = randomBytes(32).toString('hex'); const tokenId = randomBytes(16).toString('hex'); const refreshTokenHash = hashToken(refreshToken); const expiresAt = new Date( Date.now() + 7 * 24 * 60 * 60 * 1000, ); await this.sessionsService.createSession({ userId: user._id.toString(), sessionId, expiresAt, ip: req.ip, userAgent: req.headers['user-agent'], }); await this.sessionsService.createRefreshToken({ userId: user._id.toString(), sessionId, tokenHash: refreshTokenHash, tokenId, expiresAt, ip: req.ip, userAgent: req.headers['user-agent'], }); const accessToken = await this.tokenService.createAccessToken({ userId: user._id.toString(), sessionId, }); res.cookie( 'refresh_token', refreshToken, { httpOnly: true, secure: this.configService.get( 'NODE_ENV', ) === 'production', sameSite: 'strict', path: '/auth', maxAge: 7 * 24 * 60 * 60 * 1000, }, ); return { accessToken, }; } Let's walk through the key features of this code:
- First, we normalize the email. The email is trimmed and lowercased so
User@Example.comanduser@example.comfind the same account. - Then we have a generic credential error. There are two places where login can fail: the email doesn't match any user, or the password doesn't match the stored hash. In both cases, the code throws the same
UnauthorizedException('Invalid credentials'), which NestJS returns to the client as a401 Unauthorizedresponse with that message. - Next, we verify the password with
bcrypt.compare(). The submitted password is checked against the storedpasswordHash, never against a plain-text password. - Then we create the records. On success, the code generates random identifiers and a random refresh token, hashes the refresh token with SHA-256, and stores the session and the refresh-token record (only the hash, never the raw token) in MongoDB. Both expire in seven days.
- After that, we return only what the client needs. The response body contains only the short-lived
accessToken. The raw refresh token goes to the browser in a cookie, not in the JSON body. - Finally, we have cookie settings.
httpOnlyhides the cookie from JavaScript,secure(in production) means it's only sent over HTTPS,sameSite: 'strict'limits when the browser attaches it, andpath: '/auth'means the browser only sends it to/authendpoints, not every API request.
So why shouldn't we reveal whether the email or the password was wrong? Imagine the API answered "No account with this email" for one case and "Wrong password" for the other. An attacker could then submit a long list of email addresses and learn exactly which ones have accounts on your system.
That's called user enumeration, and it helps with targeted password guessing, credential stuffing, and phishing. With one identical Invalid credentials response, the attacker learns nothing about which half of the credentials was wrong.
One more detail to be aware of: in this example, when the user doesn't exist the code returns immediately without running bcrypt.compare(), so that response can be measurably faster than one for a wrong password. A hardened implementation can compare against a dummy hash in that case so both paths take similar time, and combine this with the rate limiting we'll add later.
Why HttpOnly?
HttpOnly is an attribute you can set on a cookie. It tells the browser: "Keep this cookie for HTTP requests only, and don't let page JavaScript read it." The server sets the attribute when it sends the cookie, and the browser enforces it.
Here's what the server's response looks like after login (shortened, with an example value):
Set-Cookie: refresh_token=9f2c...e81a; HttpOnly; Secure; SameSite=Strict; Path=/auth; Max-Age=604800 If any script on the page then tries to read cookies through the standard browser API, the refresh_token cookie isn't there:
console.log(document.cookie); // "" ← refresh_token isn't included, because it's HttpOnly The code block above shows two things: the HttpOnly flag on the cookie the server sends, and what JavaScript sees when it asks for cookies. JavaScript can't read the value because the browser deliberately leaves HttpOnly cookies out of document.cookie. The cookie is stored and managed by the browser itself, not by the page's JavaScript, and the browser only reads it when it needs to attach it to an outgoing request.
But the browser still attaches the cookie automatically to matching requests, like POST /auth/refresh. That's why cookie-based endpoints require CSRF-aware design, which we'll cover later.
So the path for the refresh token looks like this:
Server sets cookie (HttpOnly) ↓ Browser stores it ↓ Page JavaScript asks for cookies → refresh_token is not visible ↓ Browser itself attaches it to matching requests (for example POST /auth/refresh) Why is this the best approach here, and how does it defend against token theft? The most common way to steal a token from a web page is to run malicious JavaScript in it (XSS), read the token, and send it to a server the attacker controls. If the refresh token is in an HttpOnly cookie, that script has nothing to read, so it can't copy the long-lived credential and use it later from the attacker's own machine. This is an important defense against token theft through client-side JavaScript. It's not a complete defense: a malicious script running in the page can still make requests as the user while the page is open, which is why we need the other protections in this tutorial.
15. Angular AuthService
The AuthService is the single place in the Angular app that talks to the authentication endpoints and holds the access token. Components never call /auth/login or store tokens themselves. They ask the service.
That's what we mean when we say the service centralizes authentication requests and the in-memory access-token value: the HTTP calls for login, refresh, and logout all live in one class, and the access token lives in one private field inside it. Because the token is a plain class property (not localStorage), it's gone after a page reload, and every part of the app gets the same current value from one source of truth.
The withCredentials: true option on each request tells the browser to include cookies and accept Set-Cookie headers on cross-origin requests. Without it, the refresh cookie wouldn't be stored or sent when Angular and the API run on different origins.
In a real app, you'd want to connect the response to your application state, handle errors, and refresh on application startup if you want to restore a valid session after a reload.
@Injectable({ providedIn: 'root', }) export class AuthService { private accessToken: string | null = null; private readonly apiUrl = 'http://localhost:3000/auth'; constructor( private readonly http: HttpClient, ) {} login(credentials: LoginRequest) { return this.http.post<LoginResponse>( `${this.apiUrl}/login`, credentials, { withCredentials: true, }, ); } refresh() { return this.http.post<LoginResponse>( `${this.apiUrl}/refresh`, {}, { withCredentials: true, }, ); } logout() { return this.http.post( `${this.apiUrl}/logout`, {}, { withCredentials: true, }, ); } setAccessToken(token: string) { this.accessToken = token; } getAccessToken() { return this.accessToken; } clearAccessToken() { this.accessToken = null; } } The access token is held in ordinary Angular memory and is lost on a full page reload. Because the refresh token is in an HttpOnly cookie, Angular can't read it to restore the access token directly. The app has to call the refresh endpoint on startup and handle failure by returning the user to a signed-out state.
You'll need to protect this endpoint against CSRF and configure it to allow credentials only from the intended frontend origin.
The important architecture is:
Access Token ↓ Angular memory Refresh Token ↓ Browser HttpOnly Cookie Angular Interceptor
An interceptor is a piece of code that sits between your Angular app and the network. Every HTTP request made with HttpClient passes through it on the way out (and every response on the way back), so it can inspect or change them. That makes it useful for applying cross-cutting HTTP behavior in one place.
"Cross-cutting" means behavior that applies to many requests regardless of which feature made them, such as adding an authorization header, logging, or handling errors. Without an interceptor, you'd have to repeat that logic in every service that calls the API.
You should keep it narrowly scoped to your API, and make sure it doesn't overwrite an existing authorization header unexpectedly or attach credentials to unrelated origins.
Every protected request should automatically receive the access token when one is available. The interceptor should avoid attaching it to unrelated third-party URLs and shouldn't recursively attempt to refresh requests made to the login or refresh endpoints.
Every protected request should automatically receive:
Authorization: Bearer <accessToken> export const authInterceptor: HttpInterceptorFn = (req, next) => { const authService = inject(AuthService); const token = authService.getAccessToken(); const authReq = token ? req.clone({ setHeaders: { Authorization: `Bearer ${token}`, }, }) : req; return next(authReq); }; 16. Handling Expired Access Tokens
Access tokens are short-lived on purpose, so every client eventually runs into an expired one. In this section, we'll look at how the app detects that case, what goes wrong when several requests fail at once, and how Angular and NestJS cooperate to fix it.
Suppose the access token is expired. The backend returns 401 Unauthorized when the access token is missing, invalid, or expired. A 401 doesn't always mean the token expired, so refresh should be attempted only for relevant protec...