@greudev/nest-auth
v0.1.1
Published
Passive authentication and authorization module for NestJS microservices consuming JWT Bearer tokens from OAuth2/OIDC providers
Readme
@greudev/nest-auth
Passive authentication and authorization module for NestJS microservices consuming JWT Bearer tokens from OAuth2/OIDC providers.
Requirements
- pnpm v10+
Features
- JWT validation via JWKS (JSON Web Key Set) with cryptographic signature verification
- Strict issuer and audience validation
- Flexible user ID resolution — configurable claim keys to find the user ID (
sub,user_id, etc.) - Permission-based authorization via
@RequirePermission()decorator - Current user extraction via
@CurrentUser()parameter decorator - Configurable permissions claim (defaults to
cognito:groups)
Installation
pnpm add @greudev/nest-authUsage
1. Import the module
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { KaribuNestAuthModule } from '@greudev/nest-auth';
@Module({
imports: [
KaribuNestAuthModule.forRootAsync({
imports: [ConfigModule],
useFactory: (config: ConfigService) => ({
issuer: config.getOrThrow('OAUTH2_ISSUER'),
jwksUrl: config.getOrThrow('OAUTH2_JWKS_URL'),
audience: config.get('OAUTH2_AUDIENCE'),
userIdClaimKeys: ['cognito:username', 'sub'],
}),
inject: [ConfigService],
}),
],
})
export class AppModule {}2. Protect endpoints
import { Controller, Get, UseGuards } from '@nestjs/common';
import { KaribuAuthGuard, RequirePermission, CurrentUser } from '@greudev/nest-auth';
@Controller('orders')
@UseGuards(KaribuAuthGuard)
export class OrdersController {
@Get()
@RequirePermission('orders:read')
findAll(@CurrentUser() user: any) {
// `user.id` is the resolved user ID (from the first matching claim key)
// `user.cognito:groups` contains the permission groups
}
@Get('profile')
getProfile(@CurrentUser('email') email: string) {
// Returns only the `email` claim from the JWT
}
}Static configuration
KaribuNestAuthModule.forRoot({
issuer: 'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxx',
jwksUrl: 'https://cognito-idp.us-east-1.amazonaws.com/us-east-1_xxx/.well-known/jwks.json',
userIdClaimKeys: ['sub'],
})Configuration Options
| Option | Type | Required | Default | Description |
|---|---|---|---|---|
| issuer | string | yes | — | OIDC issuer URL (must match the iss claim exactly) |
| jwksUrl | string | yes | — | JWKS endpoint URL for public key retrieval |
| audience | string | no | — | Expected aud claim value |
| userIdClaimKeys | string[] | yes | — | Ordered list of JWT claims to resolve the user ID (e.g. ['user_id', 'sub']) |
| permissionsClaim | string | no | cognito:groups | JWT claim containing the permission array |
