0
0
NestJSframework~5 mins

Why authentication secures NestJS APIs

Choose your learning style9 modes available
Introduction

Authentication helps protect your NestJS APIs by making sure only the right people can use them. It stops strangers from accessing private data or actions.

When you want to keep user data safe from strangers.
When your API has actions only certain users should do, like editing or deleting.
When you want to track who is using your API and what they do.
When you want to give different access levels to different users.
When you want to prevent misuse or attacks on your API.
Syntax
NestJS
Use Guards and Strategies in NestJS to check user identity.

Example:
@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    // Check user token or credentials here
    return true; // or false
  }
}

Guards run before your API code to check if the user is allowed.

Strategies define how to check user identity, like using JWT tokens.

Examples
This guard checks if the request has an authorization header before allowing access.
NestJS
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    return Boolean(request.headers.authorization);
  }
}
This strategy extracts a JWT token from the header and verifies it to identify the user.
NestJS
import { Injectable } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';

// Define JWT strategy to extract and verify token
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: 'secret'
    });
  }

  validate(payload: any) {
    return { userId: payload.sub, username: payload.username };
  }
}
Sample Program

This simple controller has one route protected by the AuthGuard. Only requests passing the guard can get the profile message.

NestJS
import { Controller, Get, UseGuards } from '@nestjs/common';
import { AuthGuard } from './auth.guard';

@Controller('profile')
export class ProfileController {
  @Get()
  @UseGuards(AuthGuard)
  getProfile() {
    return { message: 'This is a protected profile data.' };
  }
}
OutputSuccess
Important Notes

Always protect sensitive routes with authentication guards.

Use HTTPS to keep tokens safe during transfer.

Test your guards to make sure unauthorized users are blocked.

Summary

Authentication stops strangers from using your API.

NestJS uses guards and strategies to check user identity.

Protect routes by applying guards to keep data safe.