GraphQL Integration
The @nestjs-cognito/graphql
package provides GraphQL-specific decorators and guards for authentication and authorization.
Installation
pnpm add @nestjs-cognito/graphql
Basic Setup
Configure the core authentication module:
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 {}
Authentication
Protect your GraphQL operations using the @GqlAuthentication()
decorator:
import { GqlAuthentication } from '@nestjs-cognito/graphql';
@Resolver()
export class SecureResolver {
@Query()
@GqlAuthentication()
async secureData() {
return { message: 'This is secure data' };
}
}
Authorization
Implement role-based access control with the @GqlAuthorization()
decorator:
import { GqlAuthorization } from '@nestjs-cognito/graphql';
@Resolver()
export class AdminResolver {
@Mutation()
@GqlAuthorization(['admin'])
async adminOperation() {
return { success: true };
}
}
User Information
Access the authenticated user's information using the GraphQL Cognito decorators:
Generic Decorator
import { GqlCognitoUser } from '@nestjs-cognito/graphql';
import type { CognitoJwtPayload } from '@nestjs-cognito/core';
@Resolver()
export class UserResolver {
@Query()
@GqlAuthentication()
async me(@GqlCognitoUser() user: CognitoJwtPayload) {
return {
id: user.sub,
username: user.username,
email: user.email
};
}
}
Specialized Decorators
For better type safety, use @GqlCognitoAccessUser
or @GqlCognitoIdUser
:
import { GqlCognitoIdUser, GqlCognitoAccessUser } from '@nestjs-cognito/graphql';
import type { CognitoIdTokenPayload, CognitoAccessTokenPayload } from '@nestjs-cognito/core';
@Resolver()
export class UserResolver {
// For ID tokens
@Query()
@GqlAuthentication()
async profile(@GqlCognitoIdUser() user: CognitoIdTokenPayload) {
return {
username: user['cognito:username'],
email: user.email,
groups: user['cognito:groups']
};
}
// For access tokens
@Query()
@GqlAuthentication()
async tokenInfo(@GqlCognitoAccessUser() token: CognitoAccessTokenPayload) {
return {
scope: token.scope,
clientId: token.client_id
};
}
}
The specialized decorators validate token types at runtime and throw CognitoTokenTypeMismatchError
if the token type doesn't match.