# Guards और Authentication — नेस्टजेएस

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

> Guards के साथ routes को protect करें और access control को enforce करें।

## Guard बनाएँ

एक guard एक class है जो `CanActivate` को implement करती है। Allow करने के लिए `true` return करें, reject करने के लिए `false`।

```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;
    }
  }
}
```

## Guard लागू करें

Routes या controllers पर `@UseGuards()` decorator उपयोग करें।

```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 `@nestjs/passport` के साथ आता है seamless authentication के लिए—JWT, OAuth, local, आदि।
