Authentication
When a user logs in through Cognito, they get a JWT token. Your NestJS app needs to verify that token before allowing access to protected routes.
Here's how the @Authentication() decorator does that for you.
Setup
First, configure the module with your Cognito User Pool:
import { CognitoAuthModule } from '@nestjs-cognito/auth';
@Module({
imports: [
CognitoAuthModule.register({
jwtVerifier: {
userPoolId: 'us-east-1_xxxxxx',
clientId: 'your-client-id',
tokenUse: 'access',
},
})
]
})
export class AppModule {}
Protecting routes
You can add @Authentication() to a controller or to individual routes.
On the entire controller
Every route in this controller requires authentication:
import { Authentication } from '@nestjs-cognito/auth';
import { Controller, Get } from '@nestjs/common';
@Controller('users')
@Authentication()
export class UsersController {
@Get()
findAll() {
return 'This route is protected';
}
}
On specific routes
Only the decorated route requires authentication:
import { Authentication } from '@nestjs-cognito/auth';
import { Controller, Get } from '@nestjs/common';
@Controller('users')
export class UsersController {
@Get('public')
public() {
return 'This route is public';
}
@Get('protected')
@Authentication()
protected() {
return 'This route is protected';
}
}
Making exceptions
If you protect a controller but need specific routes to be public, use @PublicRoute():
import { Authentication, PublicRoute } from '@nestjs-cognito/auth';
import { Controller, Get } from '@nestjs/common';
@Controller('users')
@Authentication()
export class UsersController {
@PublicRoute()
@Get('public')
public() {
return 'This route is public despite controller-level authentication';
}
}