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

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/config loads environment configuration and exposes it through ConfigService.
  • @nestjs/mongoose integrates Mongoose models with NestJS. mongoose defines schemas and communicates with MongoDB.
  • @nestjs/jwt signs and verifies JWTs.
  • @nestjs/passport, passport, and passport-jwt connect Passport strategies to NestJS authentication flows.
  • bcrypt hashes passwords and compares login attempts against stored password hashes.
  • cookie-parser parses the incoming Cookie header so Express requests can expose parsed cookies. Register its middleware in the application bootstrap if your setup requires it.
  • class-validator and class-transformer support DTO validation and transformation when used with NestJS's ValidationPipe.
  • ioredis is 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:

  • sessionId identifies one login (one device or browser). Every refresh token created for that login stores the same sessionId, 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 the sid claim of the access JWT.
  • tokenId is a unique label for one specific refresh-token record. During rotation, the old record's replacedBy field points to the new record's tokenId, which is how we build the chain R1 → 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'
}
  • sub means subject, usually the user ID.
  • sid means Session ID
  • type prevents 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.com and user@example.com find 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 a 401 Unauthorized response with that message.
  • Next, we verify the password with bcrypt.compare(). The submitted password is checked against the stored passwordHash, 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. httpOnly hides the cookie from JavaScript, secure (in production) means it's only sent over HTTPS, sameSite: 'strict' limits when the browser attaches it, and path: '/auth' means the browser only sends it to /auth endpoints, 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 protected API requests and shouldn't loop indefinitely. If refresh fails, clear the in-memory token, stop retrying, and return the user to the signed-out flow.

How do we know which case it is? By default, all three failures produce the same response: 401 Unauthorized. But underneath, the JWT library knows why validation failed. It reports a TokenExpiredError for an expired token, a "No auth token" message when the header is missing, and errors such as an invalid signature for a tampered token. We can pass that reason to the client by overriding handleRequest in the JWT guard (the guard itself is explained in a later section):

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  handleRequest(err: any, user: any, info: any) {
    if (info?.name === 'TokenExpiredError') {
      throw new UnauthorizedException({
        message: 'Access token expired',
        code: 'TOKEN_EXPIRED',
      });
    }

    if (err || !user) {
      throw new UnauthorizedException({
        message: 'Unauthorized',
        code: 'UNAUTHORIZED',
      });
    }

    return user;
  }
}

Here, info carries the reason the JWT library rejected the token. If it's a TokenExpiredError, the guard answers with 401 and a machine-readable code of TOKEN_EXPIRED. Any other failure (missing or invalid token) gets a different code. Angular can then read error.error.code in its error handler and refresh only when the code says the token expired.

A second option is on the client: the access token's payload isn't encrypted, so Angular can decode the token and read its exp (expiry) claim to see that it's about to expire. The server's answer is still the authority, though, because the client's clock may be wrong.

What should Angular do when the token has expired? Here are the steps in plain words:

  1. A request to a protected endpoint fails with 401, and the response says the access token expired.
  2. Angular pauses that failed request instead of showing an error to the user.
  3. Angular calls POST /auth/refresh. The browser automatically attaches the HttpOnly refresh cookie, because Angular can't read it or add it itself.
  4. The backend validates the refresh token, rotates it, sets a new refresh cookie, and returns a new access token.
  5. Angular stores the new access token in memory.
  6. Angular retries the original request, this time with the new token, and hands the result to the component as if nothing had happened.
  7. If the refresh call itself fails (for example, the refresh token is expired, revoked, or was reused), Angular clears the in-memory token, stops retrying, and sends the user back to the login page.

Two safeguards matter here: never try to refresh in response to a 401 from /auth/login or /auth/refresh (that would loop forever), and retry each original request only once.

The Concurrency Problem

Imagine you have these five requests:

GET /users
GET /products
GET /orders
GET /profile
GET /notifications

All receive a 401.

Without protection, the following happens:

Request A → refresh R1
Request B → refresh R1
Request C → refresh R1
Request D → refresh R1
Request E → refresh R1

This happens easily: a dashboard page often fires several API calls at once, and they all carry the same access token, so if it expires, they all fail at the same moment. Each failed request independently decides to refresh, and each sends the same refresh cookie, R1.

But our refresh token rotation says:

R1 → R2

That means each refresh token is single-use. The first refresh request to reach the server uses R1 and gets R2 in exchange. R1 is now marked as used. The other four requests then arrive carrying R1, which the server sees as an already-used token. At best, those requests are rejected and the user is signed out for no good reason. At worst, the server treats it as token theft (we'll cover reuse detection later) and revokes the whole session.

So when we say "Only one should consume R1," we mean that only one refresh request should be sent with R1, and every other request that needs a new token should wait for that single result.

Therefore we need a shared refresh operation.

Angular Refresh Lock

A refresh lock is a way for the Angular app to make sure only one refresh request is in flight at a time. It isn't a real operating-system lock. Instead, the service keeps a variable (refreshInProgress$) that holds the refresh request while it's running:

  • The first caller finds the variable empty, starts the HTTP request, and stores it in the variable.
  • Every other caller that arrives while the refresh is running finds the variable filled and gets the same request back instead of starting a new one.
  • shareReplay(1) makes all callers share one result: they all receive the same new access token, even if they subscribe slightly late.
  • finalize() clears the variable when the request finishes, so a later expiry can start a fresh refresh.
private refreshInProgress$:
  Observable<string> | null = null;

refreshAccessToken():
  Observable<string> {

  if (this.refreshInProgress$) {
    return this.refreshInProgress$;
  }

  this.refreshInProgress$ =
    this.http
      .post<LoginResponse>(
        `${this.apiUrl}/refresh`,
        {},
        {
          withCredentials: true,
        },
      )
      .pipe(
        map(response => {
          this.setAccessToken(
            response.accessToken,
          );

          return response.accessToken;
        }),

        finalize(() => {
          this.refreshInProgress$ = null;
        }),

        shareReplay(1),
      );

  return this.refreshInProgress$;
}

The resulting structure looks like this:

A ─┐
B ─┤
C ─┼──→ one refresh request
D ─┤
E ─┘

This lock makes requests in the same Angular application instance share one refresh operation. It doesn't coordinate separate browser tabs, and it can't replace atomic token rotation on the server. The backend must still make sure that only one request can consume a particular active refresh token.

Refresh Endpoint

The refresh endpoint must read the cookie, hash the supplied token, find the matching active record, verify token and session expiry/revocation, and rotate the token safely. It should also return a new access token and set a replacement cookie only after the server-side operation succeeds.

The backend receives:

refresh_token cookie

Then:

Cookie
 ↓
SHA-256
 ↓
Find RefreshToken
 ↓
Check revokedAt
 ↓
Check expiration
 ↓
Find Session
 ↓
Check Session
 ↓
Rotate
 ↓
New Access Token

Here's what happens at each step:

  1. Read the cookie: The browser attached the raw refresh_token to the request. The server reads it from the incoming cookies.
  2. Hash it: The server computes the SHA-256 hash, because the database only contains hashes, never raw tokens.
  3. Find the record: It looks up the refresh-token record with that hash. No match means the token is unknown, so the request is rejected.
  4. Check revokedAt: If the token was already revoked or used, this is a possible reuse, and the server follows the reuse-detection policy we'll describe shortly.
  5. Check expiration: An expired refresh token is rejected, and the user has to log in again.
  6. Find and check the session: The token's sessionId points to a session. If that session is missing, expired, or revoked (for example, after logout), the request is rejected even if the token itself looks fine.
  7. Rotate: The server marks the old token as used, creates a new refresh token in the same session, and links them.
  8. Respond: The server sets the new refresh token in an HttpOnly cookie and returns a new access token in the response body.

17. Refresh Token Rotation

Rotation replaces a refresh token after it's been successfully used. The old token must become unusable as part of the same logical operation that creates the replacement. Otherwise, retries or concurrent requests can produce inconsistent session state.

Suppose R1 is currently active. The client refreshes, and the server creates R2.

At that point, the server updates the old record to say two things: it's no longer valid, and which token took its place:

R1.revokedAt = now
R1.replacedBy = R2

The database now stores a small chain. R1 points forward to R2 through replacedBy, and R2 is the one currently active:

R1
 │
 └── replacedBy → R2

R2
 │
 └── active

The browser receives R2 in a new cookie, and from now on it only sends R2. On the next refresh, the same thing repeats: R2 is retired and R3 takes over.

R2 → R3

This is token rotation. At any moment, exactly one token in the chain is valid, and every older token is permanently dead, but still stored. Keeping those dead tokens is what makes the next feature possible.

Reuse Detection

If a token that was already rotated is presented again, it may indicate theft, but it can also be caused by a legitimate request race or a retry after a response was lost. The server needs an explicit policy for distinguishing between and handling these cases.

Suppose an attacker steals R1.

The legitimate user already used it:

R1 → R2

For that reason, the request should follow this path:

R1.revokedAt != null

If R1 appears again:

POST /auth/refresh
Cookie: R1

we treat this as suspicious token reuse.

A strong response is to revoke the entire session.

So:

Session A
 ├── R1 
 ├── R2 
 └── R3 

This is much stronger than simply rejecting R1.

18. Why We Have Sessions

Our system could have used only a JWT per user, so why do we also have sessions?

Without sessions, the system has just a user and a token:

User
 ↓
JWT

The server knows who the token belongs to, but it has no concept of where the user is logged in. All tokens for a user look the same. That means the server can't tell the laptop login from the phone login, can't end just one of them, can't show the user a list of their logged-in devices, and can't tell which login a suspicious refresh attempt came from.

The only drastic option is to invalidate everything for that user, for example by changing the signing key or the user's token version.

With sessions, each login becomes its own record that tokens belong to:

User
 ├── Chrome
 │     └── Session A
 │
 ├── Android
 │     └── Session B
 │
 └── Firefox
       └── Session C

Now every refresh token and access token is tied to one session through sessionId / sid, and the server can act on one session without touching the others. For example, we can implement:

Logout current device
Logout all devices
View active sessions
Revoke one device
Detect suspicious activity

If someone steals the refresh token from the Android phone, we revoke Session B and the laptop and Firefox stay signed in. That per-device control is what sessions give us.

19. JWT Authentication in NestJS

On the server, we need a way to turn the Authorization: Bearer <token> header into a known user for every protected request. NestJS does this with Passport, using a JWT strategy that describes how to read and verify the token.

We'll use Passport:

@Injectable()
export class JwtStrategy
  extends PassportStrategy(
    Strategy,
    'jwt',
  ) {

  constructor(
    private readonly configService:
      ConfigService,
    private readonly usersService:
      UsersService,
  ) {
    super({
      jwtFromRequest:
        ExtractJwt
          .fromAuthHeaderAsBearerToken(),

      ignoreExpiration: false,

      secretOrKey:
        configService.getOrThrow<string>(
          'JWT_ACCESS_SECRET',
        ),

      algorithms: ['HS256'],
    });
  }

  async validate(payload: {
    sub: string;
    sid: string;
    type: string;
  }) {

    if (payload.type !== 'access') {
      throw new UnauthorizedException();
    }

    const user =
      await this.usersService.findById(
        payload.sub,
      );

    if (!user) {
      throw new UnauthorizedException();
    }

    return {
      userId: user._id.toString(),
      sessionId: payload.sid,
      role: user.role,
      email: user.email,
    };
  }
}

Here's how authentication works in this code. It has two phases:

  1. First, the constructor configures token verification. jwtFromRequest says to take the token from the Authorization: Bearer ... header. ignoreExpiration: false means expired tokens are rejected. secretOrKey is the secret used to verify the signature, so tampered tokens fail. algorithms: ['HS256'] restricts the accepted signing algorithm instead of trusting whatever the token claims. Passport performs all these checks before our own code runs.
  2. Second, validate() runs only after the token is verified. It first checks that the type claim is 'access' so no other kind of token can be used here. Then it loads the user from MongoDB using the sub claim, and rejects the request if the user no longer exists. Finally, it returns a small object (userId, sessionId, role, or email). Whatever validate() returns is attached to the request as req.user, which later guards and controllers use.

The role comes from the database, not from the token, so a role change takes effect on the next request. Note that this version doesn't yet check that the session (sid) is still active. As I mentioned earlier, add that check if you need immediate revocation.

JwtAuthGuard

First, what's a guard? A guard is a piece of code that decides whether a request is allowed to continue. The framework runs it before the actual route handler. If the guard allows the request, the handler runs. If it blocks it, the handler never runs.

This term appears in both frameworks, with the same idea:

  • An Angular guard runs in the browser during navigation and decides whether the router may open a page (for example, redirecting to the login page if the user isn't signed in). It's a UX feature.
  • A NestJS guard is a class with a canActivate() method that runs on the server before a controller method. It decides whether the HTTP request may reach the endpoint. This is the one that provides actual security.

JwtAuthGuard is a NestJS guard. It's built from Passport's AuthGuard('jwt'), where 'jwt' is the name we gave our JwtStrategy. When a request arrives, the guard runs the strategy: it extracts and verifies the token, calls validate(), and, if all goes well, puts the result on req.user and lets the request through. If anything fails, it responds with 401 Unauthorized, and the controller never runs. It relies on verified server-side claims, not on values sent in arbitrary request fields.

@Injectable()
export class JwtAuthGuard
  extends AuthGuard('jwt') {}

Now:

@Get('me')
@UseGuards(JwtAuthGuard)
me(@Req() req: Request) {
  return req.user;
}

Here, @UseGuards(JwtAuthGuard) attaches the guard to the me endpoint. Only requests with a valid access token get through, and the handler returns the authenticated user that the strategy stored on req.user.

The backend becomes the true security boundary. Angular guards are only for navigation UX.

Angular Guard Isn't Security

Angular guards improve navigation and user experience, but users can bypass browser code and call the API directly. So you should enforce all authentication and authorization rules in NestJS as well.

This is a very important rule:

Angular Guard
      ↓
UX / Navigation

NestJS Guard
      ↓
Security

An attacker can completely bypass Angular. For example, they can send requests directly from the command line with a tool like curl:

curl ...

or with other tools that send raw HTTP requests without running your frontend at all:

Postman
Burp Suite
custom script

Postman is an API client, Burp Suite is a security-testing proxy that can capture and modify requests, and a custom script is any program that calls your API's URLs directly. None of them run your Angular code, so none of them are stopped by an Angular guard.

Therefore every sensitive endpoint must enforce authorization on the backend.

20. RBAC

Authentication tells us who the user is. Next we need to decide what they're allowed to do. A common way to do that is with roles.

A role is a label attached to a user that describes a broad level of access. Our application uses three:

  • USER: a regular account. It can use the application normally and manage its own data.
  • MODERATOR: a trusted account with extra powers over content or other users' behavior, such as removing inappropriate posts.
  • ADMIN: a fully trusted account that can manage the system, such as listing, changing, or deleting user accounts.

Role-Based Access Control (RBAC) maps users to roles and roles to broad capabilities. You should keep role assignment under trusted server-side control. For example, a registration request must never be allowed to set its own role.

Our roles are as follows:

export enum UserRole {
  USER = 'user',
  MODERATOR = 'moderator',
  ADMIN = 'admin',
}

A role answers which broad actions a user may perform: "Can this person access the admin area at all?" That's different from resource-level authorization, which answers whether this user may act on this particular record: "Can this person open order #123?"

Two regular users both have the USER role, but neither should read the other's orders. So for every endpoint that works with a specific record (an order, a profile, a document), also check in the service layer that the record belongs to the current user, or that they have an explicit permission for it. Roles alone aren't enough for those endpoints.

In the next few subsections, we'll build the role-checking pieces: a decorator to declare which roles an endpoint needs, a guard that enforces it, and then an example of using them together.

@Roles()

We want a simple way to say, right on a controller method, which roles may call it. NestJS lets us attach custom information (called metadata) to a route with SetMetadata. The @Roles() decorator is a small wrapper around that. It stores the list of allowed roles on the route, so the guard that we write next can read it:

export const ROLES_KEY = 'roles';

export const Roles =
  (...roles: UserRole[]) =>
    SetMetadata(
      ROLES_KEY,
      roles,
    );

The decorator doesn't enforce anything by itself. It only labels the route. For example:

@Roles(UserRole.ADMIN)

means:

Only ADMIN users

You can pass more than one role, such as @Roles(UserRole.ADMIN, UserRole.MODERATOR), meaning either role is allowed.

RolesGuard

RolesGuard is the code that enforces what @Roles() declares. It uses NestJS's Reflector to read the roles stored on the route, and compares them with the role of the current user (request.user, which JwtAuthGuard already filled in).

@Injectable()
export class RolesGuard
  implements CanActivate {

  constructor(
    private readonly reflector:
      Reflector,
  ) {}

  canActivate(
    context: ExecutionContext,
  ): boolean {

    const requiredRoles =
      this.reflector.getAllAndOverride<
        UserRole[]
      >(
        ROLES_KEY,
        [
          context.getHandler(),
          context.getClass(),
        ],
      );

    if (!requiredRoles) {
      return true;
    }

    const request =
      context
        .switchToHttp()
        .getRequest();

    const user =
      request.user;

    if (!user) {
      throw new UnauthorizedException();
    }

    if (
      !requiredRoles.includes(
        user.role,
      )
    ) {
      throw new ForbiddenException(
        'Insufficient permissions',
      );
    }

    return true;
  }
}

What's happening in this code:

  1. getAllAndOverride reads the roles metadata, first from the method and then from the controller class, so a role set on a method overrides one set on the whole class.
  2. If no roles are required (no @Roles()), the guard lets the request through.
  3. It gets the current request and its user. If there's no user, authentication didn't happen, so it throws 401.
  4. If the user's role isn't in the list of required roles, it throws 403 Forbidden ("Insufficient permissions").
  5. Otherwise, it returns true and the request continues to the controller.

Using RBAC

Now we can combine everything on an endpoint. This route lists all users, which should only be allowed for admins:

@Get('users')
@UseGuards(
  JwtAuthGuard,
  RolesGuard,
)
@Roles(UserRole.ADMIN)
findUsers() {
  return this.usersService.findAll();
}

@UseGuards(JwtAuthGuard, RolesGuard) runs the two guards in order: first authenticate, then check the role. @Roles(UserRole.ADMIN) tells RolesGuard which role is needed. Order matters: RolesGuard depends on req.user, which only exists after JwtAuthGuard has run.

The request goes through this flow:

Request
   ↓
JWT valid?
   │
   ├── No → 401
   │
   ▼
User identified
   ↓
Role = admin?
   │
   ├── No → 403
   │
   ▼
Controller

401 vs 403

This distinction is extremely important, because the two codes tell the client two different things, and the client reacts differently to each.

401

A 401 Unauthorized response means the server doesn't know who you are, or couldn't verify it. The request has no valid identity. The fix is to authenticate (or re-authenticate), and in our app, a 401 is what triggers a token refresh or sends the user to login.

Authentication failed

Examples:

Missing token
Invalid token
Expired token
Invalid credentials

403

A 403 Forbidden response means the server knows exactly who you are, and you're not allowed to do this. Logging in again or refreshing the token won't help, because the identity was fine. The user simply doesn't have permission, so the client should show an "access denied" message instead of retrying.

Authentication succeeded
but authorization failed

Example:

User = USER
Required = ADMIN

This is important because mixing them up causes real problems: if you return 401 for a permissions problem, the Angular app will try to refresh and loop, and if you return 403 for a missing token, the app won't know it should re-authenticate. A quick way to remember them:

401 → Who are you?

403 → We know who you are,
      but you're not allowed.

Public Routes

If protection is the default, we need a way to mark the few endpoints that must stay open, such as login and registration. Instead of manually adding guards everywhere, we can create a @Public() decorator. It uses the same metadata technique as @Roles():

export const IS_PUBLIC_KEY =
  'isPublic';

export const Public = () =>
  SetMetadata(
    IS_PUBLIC_KEY,
    true,
  );

Then we apply it to the routes that should be open, for example the login endpoint:

@Post('login')
@Public()
login() {}

This allows us to make authentication guards global. Making a guard global means registering it once for the whole application (for example, as an APP_GUARD) so it runs on every route automatically, instead of adding @UseGuards(JwtAuthGuard) to each controller or method. The global guard checks for @Public() first: if the route has it, the request is allowed through, and otherwise normal JWT authentication runs.

The architecture becomes:

Request
  ↓
Global Auth Guard
  ↓
@Public()?
 ├── yes → allow
 └── no
      ↓
JWT authentication
      ↓
Authorization

This is often safer because new endpoints are protected by default. If a developer forgets to add a guard to a new route, it's still protected, and opening a route to the public has to be a deliberate choice.

21. CSRF

Cross-Site Request Forgery matters when a browser automatically attaches credentials, such as cookies, to a request. HttpOnly protects cookie confidentiality from JavaScript but doesn't stop the browser from sending the cookie.

Our refresh token is stored in a cookie. Cookies have an important property: browsers automatically attach them to requests according to cookie rules.

That creates CSRF considerations. The main issue is this: a request is sent with the user's valid cookie, but the user never intended to send it. The server sees a valid cookie and can't tell by the cookie alone whether the request came from our own app or from another website. For state-changing endpoints such as /auth/refresh or /auth/logout, that lets a malicious site trigger actions in the context of a logged-in user.

Suppose:

User logged into our-app.com

then visits

evil.com

The malicious site may try to cause:

POST https://our-app.com/auth/refresh

The browser manages cookies automatically. To combat against this issue, we can add CSRF defenses. In the next subsections, we'll look at three: the SameSite cookie attribute, a CSRF token, and a guard that checks it.

SameSite

SameSite is a cookie attribute that tells the browser when it may send the cookie on requests that start from a different site. With Strict, the browser only sends the cookie when the request comes from the same site as the cookie. With Lax, it also sends it on top-level navigations such as clicking a link. With None, it sends it on all cross-site requests (and requires Secure).

Our refresh cookie can use:

sameSite: 'strict'

This is a useful defense-in-depth setting, but it's not a complete CSRF strategy. Cookie behavior depends on the relationship between frontend and backend sites, cookie domain/path, and whether credentials are enabled in the client and CORS configuration.

But cookie behavior depends on whether the frontend and backend are same-origin, same-site, or cross-site.

For cross-site deployments, you may need:

SameSite=None
Secure=true

plus explicit CSRF protection. The client must use withCredentials: true, and the API must allow credentials for the exact trusted frontend origin. You should never combine credentialed requests with a wildcard CORS origin.

So, make sure you design your cookie configuration together with your deployment architecture. SameSite is defense in depth. It isn't a substitute for validating state-changing requests.

CSRF Token

A CSRF token is a random value that the server gives to our own frontend, and that the frontend must send back with every state-changing request. A malicious site can make the browser attach cookies, but it can't read our cookies or set custom headers on our domain, so it can't produce the matching token. The server accepts the request only if the token in the header matches the one in the cookie.

A common pattern is:

HttpOnly Cookie
refresh_token

Regular Cookie
csrf_token

The csrf_token is a normal (not HttpOnly) cookie so that Angular can read it. Angular reads:

csrf_token

and sends it back in a custom header:

X-CSRF-Token: <token>

Then the server checks that the two values are the same:

Cookie csrf_token
        ==
X-CSRF-Token

The refresh token itself remains HttpOnly.

CSRF Guard

The CSRF guard is the NestJS guard that performs that check on the server. We'll look at the code, which skips safe methods (they don't change state) and rejects any other request whose cookie and header tokens are missing or different.

@Injectable()
export class CsrfGuard
  implements CanActivate {

  canActivate(
    context: ExecutionContext,
  ): boolean {

    const request =
      context
        .switchToHttp()
        .getRequest();

    const safeMethods = [
      'GET',
      'HEAD',
      'OPTIONS',
    ];

    if (
      safeMethods.includes(
        request.method,
      )
    ) {
      return true;
    }

    const cookieToken =
      request.cookies?.csrf_token;

    const headerToken =
      request.headers[
        'x-csrf-token'
      ];

    if (
      !cookieToken ||
      !headerToken ||
      cookieToken !== headerToken
    ) {
      throw new ForbiddenException(
        'Invalid CSRF token',
      );
    }

    return true;
  }
}

In a production system, you'd want to compare the two token values using a constant-time comparison and consider checking the request's Origin as an additional defense. The application must also generate a cryptographically unpredictable CSRF token and provide it to Angular through a deliberate mechanism.

Comparing the cookie and header is only one part of the design, so you'll want to verify the complete flow against your actual frontend and backend domains and proxy configuration.

22. Redis

Redis is useful for short-lived shared state, including rate-limit counters, because multiple API instances can use the same store. It shouldn't become the only durable record of user identity or long-lived sessions unless that's an explicit architectural choice.

Redis isn't our main database here. In our case, MongoDB stores users, sessions, and RefreshTokens

Redis is useful for rate limits, temporary counters, short-lived locks, OTP state, temporary authentication state, and caching.

This is an important architectural principle: don't add Redis simply because production systems use Redis. Use it where its characteristics solve a real problem.

Rate Limiting

Rate limiting reduces abuse by limiting repeated attempts over a time window. You should choose limits based on endpoint risk and user experience, and return a consistent 429 Too Many Requests response when a client exceeds them.

Consider:

POST /auth/login

An attacker can send 1000 requests in a short period.

We can maintain a Redis counter:

auth:login:ip:<ip>

and increment it like this:

const attempts =
  await redisService.increment(
    key,
    60,
  );

if (attempts > 10) {
  throw new TooManyRequestsException();
}

Here's what this code is doing. key is the counter's name, built from the pattern above (for example, auth:login:ip:203.0.113.7), so each IP address gets its own counter. redisService.increment(key, 60) is a helper that adds 1 to that counter in Redis and returns the new value. The 60 is the window length in seconds: the first time the key is created, it's given a time-to-live (TTL) of 60 seconds, after which Redis deletes it automatically and the count starts again.

Then the code compares the count with the limit. In this example, more than 10 login attempts from one IP within 60 seconds causes the request to be rejected with a 429 Too Many Requests error instead of checking the password.

The first request creates:

counter = 1
TTL = 60 seconds

Then:

2
3
4
...

Because Redis is shared, the count is the same no matter which API instance handles the request. Note that TooManyRequestsException is a helper that produces the 429 response. If you don't have one in your project, you can throw an HttpException with status 429.

Don't Rate Limit Only by IP

IP-only rate limiting can hurt legitimate users.

For example:

Company
   ↓
NAT
   ↓
100 users
   ↓
same public IP

A better strategy can combine:

IP
+
Account identifier
+
IP + account

For example:

auth:login:ip:<ip>

auth:login:email:<hash>

auth:login:ip-email:<ip>:<hash>

Different limits can be applied to each dimension.

Endpoints Worth Protecting

Authentication-related endpoints deserve special attention:

POST /auth/login
POST /auth/register
POST /auth/refresh
POST /auth/forgot-password
POST /auth/reset-password
POST /auth/verify-email
POST /auth/change-password

Especially:

login
refresh
forgot-password

because they're attractive targets for abuse.

23. CORS

CORS is a browser policy controlling which origins may read cross-origin responses. It's not authentication and doesn't stop non-browser clients from calling an API.

Two terms here need explaining. An origin is the combination of scheme, host, and port, such as http://localhost:4200. A credentialed request is a cross-origin request where the browser includes credentials, such as cookies, which is what Angular's withCredentials: true does.

For credentialed requests, the browser requires the API to name an explicit allowed origin (the exact origin of your frontend) rather than a wildcard. The wildcard is *, which means "any origin may do this," and browsers refuse to accept it when credentials are involved.

Angular might run at:

http://localhost:4200

while NestJS runs at:

http://localhost:3000

Because these are different origins (the ports differ), the browser applies CORS rules. We can configure the API like this:

app.enableCors({
  origin:
    'http://localhost:4200',

  credentials: true,
});

This configuration does two things. origin tells the API to allow cross-origin requests from only the Angular app at http://localhost:4200, so the response includes a matching Access-Control-Allow-Origin header. credentials: true adds Access-Control-Allow-Credentials: true, which lets the browser send and accept cookies (like our refresh cookie) on those requests.

In production, don't use:

origin: '*'

with credentialed requests. Use explicit trusted origins.

24. Logout

Logout should revoke the current server-side refresh/session state and clear the refresh cookie using matching cookie attributes. Clearing the Angular access token alone only signs the current UI out. It doesn't invalidate a stolen token on the server.

Logout should revoke the current session.

@Post('logout')
@UseGuards(JwtAuthGuard)
async logout(
  @Req() req: Request,
  @Res({
    passthrough: true,
  })
  res: Response,
) {
  await this.sessionsService
    .revokeSession(
      req.user.sessionId,
    );

  res.clearCookie(
    'refresh_token',
    {
      httpOnly: true,
      secure:
        this.configService.get(
          'NODE_ENV',
        ) === 'production',
      sameSite: 'strict',
      path: '/auth',
    },
  );

  return {
    message:
      'Logged out successfully',
  };
}

Notice something important here: the current access JWT may remain technically valid until it expires. This is a deliberate trade-off.

Logout All Devices

Logout-all should revoke the authenticated user’s active sessions and associated refresh tokens. Make sure the user ID comes from the verified request identity, not from an arbitrary ID submitted by the client.

Because we have Sessions:

User
 ├── Session A
 ├── Session B
 └── Session C

we can do the following:

await sessionsService
  .revokeAllUserSessions(
    userId,
  );

What's happening here: revokeAllUserSessions finds every active session that belongs to this user in MongoDB and marks each one as revoked (and revokes their refresh tokens). The userId should come from the authenticated request (req.user.userId), never from the request body, so users can only log themselves out. This is the "sign out everywhere" button you see in many apps, and it's also useful after a password change or a suspected compromise.

The resulting structure looks like this:

Session A 
Session B 
Session C 

All three are now revoked. Any future refresh attempt fails, and every device has to log in again once its short-lived access token expires.

25. MongoDB Transaction for Rotation

When one refresh operation updates multiple MongoDB documents, those writes need consistent failure behavior. MongoDB multi-document transactions require a replica set (including a properly configured single-node replica set for local development) or a supported sharded deployment. They don't work on a standalone MongoDB server.

There's another production consideration.

Suppose rotation performs the following:

revoke R1
create R2

What if the application crashes between those operations?

We might get:

R1 = revoked
R2 = not created

So when appropriate, use a MongoDB transaction:

BEGIN
   ↓
revoke R1
   ↓
create R2
   ↓
update session
   ↓
COMMIT

If something fails, you can always rollback.

This makes rotation atomic only when the database deployment supports transactions and all related writes are included in the transaction.

MongoDB multi-document transactions require a replica set (including a properly configured single-node replica set for local development) or a supported sharded deployment. They don't work on a standalone MongoDB server. Conditional updates are still needed to ensure that only one request consumes a particular active refresh token.

26. Complete Authentication Flow

Let's put everything together. The following subsections walk through the complete life of an authenticated user, in order: logging in, making ordinary requests, handling an expired token, what happens when a refresh token is stolen, and how authorization decisions are made.

Login

Angular
   │
   │ email/password
   ▼
NestJS
   │
   ├── validate DTO
   ├── rate limit
   ├── find user
   ├── bcrypt.compare
   │
   ├── create session
   ├── create R1
   ├── store SHA-256(R1)
   ├── create access JWT
   │
   └── Set-Cookie R1
          │
          ▼
       Angular
       accessToken

Normal API Request

Angular
   │
   │ Authorization: Bearer JWT
   ▼
NestJS
   │
   ▼
JwtAuthGuard
   │
   ▼
JWT validation
   │
   ▼
User
   │
   ▼
RolesGuard
   │
   ▼
Controller
   │
   ▼
Service

Expired Access Token

Angular
   │
   ▼
API
   │
   ▼
401
   │
   ▼
refreshAccessToken()
   │
   ▼
POST /auth/refresh
   │
   └── HttpOnly Cookie R1
          │
          ▼
      NestJS
          │
          ├── hash R1
          ├── find token
          ├── check expiration
          ├── check revoked
          ├── check session
          │
          ├── revoke R1
          ├── create R2
          └── create new JWT
                  │
                  ▼
              Angular
                  │
                  ▼
             retry request

Refresh Token Theft

Suppose a legitimate client and an attacker both end up with the same refresh token, R1. This could happen if the attacker copied it from a compromised device or intercepted it somewhere.

The legitimate client refreshes first, and the server rotates the token:

Legitimate client:
R1 → R2

R1 is now marked as used and replaced. Later, the attacker tries to use their copy:

R1

The server looks up R1, finds it, and sees that it was already used:

R1.revokedAt != null

A valid refresh token would never be presented a second time by a correct client, so the server treats this as a sign that two parties have the same token. Rather than just rejecting the attacker's request, it responds by shutting the whole session down:

Token reuse detected
       ↓
Revoke session
       ↓
Force re-authentication

Revoking the session also kills R2, which the legitimate user holds, so the attacker can't simply wait and use the newest token. The legitimate user is signed out and has to log in again, which is an inconvenience, but the attacker's access ends. The user logging in again creates a brand-new session with fresh tokens the attacker doesn't have.

Reuse detection is useful only when the server can distinguish a previously rotated token from a valid current token and apply a defined response. When reuse is confirmed, you should revoke the affected session (or token family) and require the user to authenticate again.

The lookup, old-token revocation, replacement-token creation, and session updates must be atomic. Otherwise, simultaneous refresh requests can create race conditions. Be careful not to treat every duplicate request as theft without considering legitimate parallel requests or a retry after a lost response.

Authorization Flow

For:

DELETE /users/123

we have:

Request
   ↓
Authentication
   ↓
user = {
   id: 123,
   role: USER
}
   ↓
RolesGuard
   ↓
Required = ADMIN
   ↓
USER != ADMIN
   ↓
403 Forbidden

27. Security Review

Use this as a review checklist, not as proof that every control is fully implemented or production-ready. Verify each item against the actual code, deployment settings, and automated tests:

Passwords

 Password hashing
 No plaintext passwords
 Strong password policy

JWT

 Short-lived access tokens
 Strong secret
 Explicit algorithm
 Minimal payload

Refresh Tokens

 Cryptographically random
 SHA-256 hash at rest
 HttpOnly cookie
 Secure cookie in production
 SameSite policy
 Rotation
 Reuse detection

Sessions

 Session per device
 Current-session logout
 Logout all
 Session revocation

Authorization

 JwtAuthGuard
 RolesGuard
 @Roles()
 401 vs 403 separation

Browser Security

 CSRF protection
 CORS restrictions
 HttpOnly cookies

Abuse Protection

 Redis rate limiting
 Login protection
 Refresh protection

API Security

 DTO validation
 whitelist
 forbidNonWhitelisted
 Database constraints
 Explicit input mapping

28. Things We Should Add Later

A real production identity system needs more than the core login and refresh flow. The items below are additional capabilities, not features that should be assumed to exist unless they're implemented, configured, and tested in the application.

Email Verification

Register
   ↓
Verification Email
   ↓
Verify Token
   ↓
emailVerified = true

Password Reset

Forgot Password
      ↓
Reset Token
      ↓
New Password
      ↓
Revoke existing sessions

MFA

Password
   +
Authenticator / Passkey / OTP

Security Events

Log:

Login success
Login failure
Logout
Password change
Password reset
Refresh reuse detection
Session revoked
Role changed

Permission-based Authorization

Instead of:

@Roles(UserRole.ADMIN)

we can eventually have:

@Permissions(
  Permission.USERS_READ,
  Permission.USERS_DELETE,
)

which scales better for complex systems.

29. The Most Important Architectural Lessons

The biggest lessons from this system are the design decisions.

Lesson 1:

Authentication and authorization are different problems.

Authentication
Who are you?

Authorization
What can you do?

Lesson 2:

A User is not a Session.

User
 ├── Session A
 ├── Session B
 └── Session C

Lesson 3:

A refresh token isn't necessarily a JWT. A random opaque token can be simpler and safer when the server already stores session state.

Lesson 4:

Never store refresh tokens in plaintext.

Store them like this:

SHA256(refreshToken)

instead.

Lesson 5:

Refresh-token rotation changes the security model.

R1 → R2 → R3

allows us to detect reuse.

Lesson 6:

Frontend guards aren't security boundaries. Backend authorization is mandatory.

Lesson 7:

Cookies introduce CSRF considerations. HttpOnly protects against JavaScript reading the cookie, but it doesn't by itself eliminate CSRF.

Lesson 8:

Rate limiting is part of authentication security. A secure password system without brute-force protection is incomplete.

Lesson 9:

Concurrency is part of security. A refresh-token rotation system must account for multiple simultaneous requests.

Lesson 10:

Production security is layered.

TLS
 ↓
CORS
 ↓
CSRF
 ↓
Authentication
 ↓
Authorization
 ↓
Validation
 ↓
Rate Limiting
 ↓
Database Constraints
 ↓
Session Security
 ↓
Monitoring

No single mechanism is enough.

30. Final Architecture

Our complete system can now be visualized like this:

                         ┌───────────────┐
                         │    Angular    │
                         └───────┬───────┘
                                 │
                    ┌────────────┴────────────┐
                    │                         │
             Access Token              Refresh Cookie
                    │                         │
             Memory only                  HttpOnly
                    │                         │
                    ▼                         ▼
              Authorization              CSRF
                 Header                 Protection
                    │                         │
                    └────────────┬────────────┘
                                 │
                                 ▼
                         ┌───────────────┐
                         │    NestJS     │
                         └───────┬───────┘
                                 │
                 ┌───────────────┼───────────────┐
                 │               │               │
                 ▼               ▼               ▼
          Rate Limiting    Authentication   Authorization
             Redis          JWT Strategy      RolesGuard
                 │               │               │
                 └───────────────┼───────────────┘
                                 │
                                 ▼
                           Application
                             Service
                                 │
                       ┌─────────┴─────────┐
                       ▼                   ▼
                   MongoDB               Redis
                       │                   │
              ┌────────┼────────┐          │
              │        │        │          │
             Users  Sessions Refresh    Rate Limits
                            Tokens       Locks

This gives us a security-oriented architecture to build on. Whether it's appropriate for production depends on the completeness of the implementation, threat model, deployment configuration, operational monitoring, and security tests.

Treat the diagram as a map of responsibilities rather than a guarantee that every control is already implemented.

The important thing is that each mechanism has a specific responsibility:

JWT
→ short-lived authentication

Refresh Token
→ session continuation

Session
→ device/session lifecycle

RBAC
→ authorization

CSRF
→ protection for cookie-based state-changing requests

Redis
→ rate limiting and temporary/distributed state

MongoDB
→ persistent identity/session data

Angular Interceptor
→ client-side token lifecycle

NestJS Guards
→ server-side security boundary

Once these responsibilities are clearly separated, the system becomes much easier to reason about, test, extend, and secure.

Explore the Source Code

You can explore the source code for this project on GitHub:

Authentication & Authorization System with Angular and NestJS

The repository provides a practical reference for the concepts discussed in this article. Feel free to explore the implementation, review the code, and experiment with the architecture as you learn how authentication and authorization work together in a modern web application.

If you find it helpful, consider starring the repository on GitHub.