cognito-auth-library
v1.0.2
Published
`TokenUtils` is a utility class for validating AWS Cognito JWT tokens using the JSON Web Key Set (JWKS). It dynamically supports multiple Cognito user pools by allowing the user pool ID and AWS region to be set at runtime. The utility fetches the public k
Readme
TokenUtils - JWT Validation Utility for AWS Cognito
TokenUtils is a utility class for validating AWS Cognito JWT tokens using the JSON Web Key Set (JWKS). It dynamically supports multiple Cognito user pools by allowing the user pool ID and AWS region to be set at runtime. The utility fetches the public key from AWS Cognito's JWKS endpoint and verifies the token against it. Additionally, it supports role-based access control by checking if the user's role matches any of the required roles.
Features
- Dynamic User Pool Support: Validate tokens from multiple Cognito user pools by dynamically setting the pool ID and region.
- Token Verification: Automatically fetch public keys from Cognito's JWKS endpoint.
- Role-based Access Control: Validate user roles based on provided required roles.
- Secure and Reliable: Handles token decoding and error handling gracefully.
Usage
Import the TokenUtils class
import { TokenUtils } from 'cognito-auth-library';Example Usage
const userPoolId = 'us-east-1_xxxxxxxx'; // Dynamic user pool ID
const region = 'us-east-1'; // Dynamic region
const token = 'eyJra...'; // JWT token
const requiredRoles = ['Admin', 'Editor'];
const tokenUtils = new TokenUtils(userPoolId, region);
async function validateUserToken() {
try {
const payload = await tokenUtils.validateTokenWithRoles(token, requiredRoles);
console.log('Token is valid');
console.log('Payload:', payload);
} catch (error) {
console.error('Token validation failed:', error.message);
}
}
validateUserToken();API Documentation
TokenUtils Class
Constructor
constructor(userPoolId: string, region: string)userPoolId(string) - The AWS Cognito User Pool ID (can be set dynamically).region(string) - The AWS region where the Cognito User Pool is deployed (can be set dynamically).
Methods
validateTokenWithRoles(token: string, requiredRoles: string[] = []): Promise<JwtPayload>
Validates a JWT token against the Cognito public key.
Parameters:
token(string) - The JWT token to be validated.requiredRoles(string[], optional) - An array of required roles to check in the token.
Returns:
A promise that resolves to the decoded JWT payload if validation succeeds. If validation fails, it throws an error.
Error Handling
If the token is invalid or missing required claims, an error is thrown with a descriptive message and an HTTP status code. The custom exceptions used are UnauthorizedException (for 401 errors) and ForbiddenException (for 403 errors).
For example:
{
"message": "Token validation failed: Invalid token format or missing 'kid'",
"statusCode": 401
}Example Responses
Successful Validation
{
"sub": "1234567890",
"email": "[email protected]",
"custom:groupV2": "Admin",
"iss": "https://cognito-idp.us-west-2.amazonaws.com/us-west-2_abcdef12",
"iat": 1737526655,
"exp": 1737562655
}Failed Validation
{
"message": "Token verification failed: Invalid token format or missing 'kid'"
}Security Considerations
- Ensure the JWT token is received securely (e.g., via HTTPS).
- Regularly rotate AWS Cognito keys and handle key rotation appropriately.
- Limit access based on roles to prevent unauthorized access.
- Since the user pool and region are dynamically set, validate inputs to avoid misconfigurations.
License
This project is licensed under the MIT License.
Author
Developed by [Sarath Baby]
