# Guards & Authentication — NestJS

Source: https://www.geekswithgeeks.com/en/nestjs/nestjs-guards-auth

> Protect routes and enforce access control with guards.

## Create a guard

A guard is a class implementing `CanActivate`. Return `true` to allow, `false` to reject.

```typescript
import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()
export class JwtGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest();
    const token = request.headers.authorization?.split(' ')[1];
    if (!token) return false;
    try {
      // verify token
      return true;
    } catch {
      return false;
    }
  }
}
```

## Apply a guard

Use `@UseGuards()` decorator on routes or controllers.

```typescript
@UseGuards(JwtGuard)
@Get('profile')
getProfile(@Request() req) {
  return req.user;
}

// or on the controller
@Controller('admin')
@UseGuards(JwtGuard)
export class AdminController { ... }
```

## Passport.js integration

NestJS ships with `@nestjs/passport` for seamless authentication—JWT, OAuth, local, etc.
