egain-ps-utils
v3.0.2
Published
eGain PS Utils. A utility package for eGain PS
Readme
egain-ps-utils
egain-ps-utils is a collection of utility functions designed to simplify common development tasks. This package provides helpers and methods to boost your development workflow, and for the 3.0.0 release, we're offering a convenient jwt authorizer utility for handling authorization-related tasks with dual module support (ESM and CommonJS).
Release Notes (3.0.2)
- Dual Module Support: Now supports both ESM (
import) and CommonJS (require) syntax - TypeScript Support: Full TypeScript definitions included
- Requires Node.js 18+ (uses native
fetch) - Improved compatibility and performance
- Updated documentation and usage examples
- Enhanced JWT authorizer utility for Azure AD
Requirements
- Node.js 18 or higher (uses native
fetch) - ps-chronicle: Use the latest version (
^1.0.6or higher) for best compatibility with this package.
Features
validateToken: A utility function to assist with authorization checks, ensuring that only authorized users can access specific resources or perform particular actions.- This validator will check for:
- token expiry
- issuer
- audience
- certificate
- This function will return a boolean value indicating whether the token is valid or not.
- This validator will check for:
generateAuthResponse: A utility function to assist with generating authorization responses. This will return a policy document with the effect and the methodArn.isTokenIssuedForValidClaimTenantId: A utility function to validate if a token is issued for a valid claim tenant ID.getDecodedJwtToken: A utility function to decode a JWT token string and return the decoded token object. This is useful for extracting claims and other information from JWT tokens without validation.
Prerequisites
- AWS Secrets Manager SDK v3 (if using with AWS Lambda and secrets)
Create a secret in AWS Secrets Manager with the following format:
{
"audience": "xxxx",
"issuer": "https://xxxx.com/xxxxxx/xx.x"
}To get the audience and issuer values, you can use the following steps:
- Get the Metadata from your identity provider.
- Use these values as the audience and issuer in the secret.
Installation
Using npm:
npm install egain-ps-utilsUsing yarn:
yarn add egain-ps-utilsUsage
ESM (ES6 Modules)
import { validateToken, generateAuthResponse, isTokenIssuedForValidClaimTenantId, getDecodedJwtToken } from 'egain-ps-utils';
const authorize = async (event) => {
try {
const authorization = event.headers.Authorization || event.headers.authorization;
if (!authorization) {
throw new Error('Authorization token is missing');
}
const secretName = 'xxxxx';
// Validate the token
const { isTokenValid } = await validateToken(authorization, secretName);
if (isTokenValid) {
return generateAuthResponse('Allow', event.methodArn);
} else {
return generateAuthResponse('Deny', event.methodArn);
}
} catch (error) {
console.error('Authorization error:', error);
return generateAuthResponse('Deny', event.methodArn);
}
};
// Example: Decode JWT token to extract claims
const extractTokenClaims = (jwtString) => {
try {
const decodedToken = getDecodedJwtToken(jwtString);
return {
userId: decodedToken.sub,
email: decodedToken.email,
tenantId: decodedToken.tid,
expiresAt: new Date(decodedToken.exp * 1000)
};
} catch (error) {
console.error('Error decoding token:', error);
return null;
}
};
export { authorize, extractTokenClaims };CommonJS
const { validateToken, generateAuthResponse, isTokenIssuedForValidClaimTenantId, getDecodedJwtToken } = require('egain-ps-utils');
const authorize = async (event) => {
try {
const authorization = event.headers.Authorization || event.headers.authorization;
if (!authorization) {
throw new Error('Authorization token is missing');
}
const secretName = 'xxxxx';
// Validate the token
const { isTokenValid } = await validateToken(authorization, secretName);
if (isTokenValid) {
return generateAuthResponse('Allow', event.methodArn);
} else {
return generateAuthResponse('Deny', event.methodArn);
}
} catch (error) {
console.error('Authorization error:', error);
return generateAuthResponse('Deny', event.methodArn);
}
};
// Example: Decode JWT token to extract claims
const extractTokenClaims = (jwtString) => {
try {
const decodedToken = getDecodedJwtToken(jwtString);
return {
userId: decodedToken.sub,
email: decodedToken.email,
tenantId: decodedToken.tid,
expiresAt: new Date(decodedToken.exp * 1000)
};
} catch (error) {
console.error('Error decoding token:', error);
return null;
}
};
module.exports = { authorize, extractTokenClaims };TypeScript
import { validateToken, generateAuthResponse, isTokenIssuedForValidClaimTenantId, getDecodedJwtToken } from 'egain-ps-utils';
interface LambdaEvent {
headers: {
Authorization?: string;
authorization?: string;
};
methodArn: string;
}
interface TokenClaims {
userId?: string;
email?: string;
tenantId?: string;
expiresAt?: Date;
}
const authorize = async (event: LambdaEvent) => {
try {
const authorization = event.headers.Authorization || event.headers.authorization;
if (!authorization) {
throw new Error('Authorization token is missing');
}
const secretName = 'xxxxx';
// Validate the token
const { isTokenValid } = await validateToken(authorization, secretName);
if (isTokenValid) {
return generateAuthResponse('Allow', event.methodArn);
} else {
return generateAuthResponse('Deny', event.methodArn);
}
} catch (error) {
console.error('Authorization error:', error);
return generateAuthResponse('Deny', event.methodArn);
}
};
// Example: Decode JWT token to extract claims
const extractTokenClaims = (jwtString: string): TokenClaims | null => {
try {
const decodedToken = getDecodedJwtToken(jwtString);
return {
userId: decodedToken.sub,
email: decodedToken.email,
tenantId: decodedToken.tid,
expiresAt: new Date(decodedToken.exp * 1000)
};
} catch (error) {
console.error('Error decoding token:', error);
return null;
}
};
export { authorize, extractTokenClaims };Notes
- This package requires Node.js 18+ for native
fetchsupport. - For best results, use the latest version of
ps-chronicle(at least 1.0.6). - For Azure AD JWT validation, ensure you provide the correct
issuer,audience, andkidin the options object. - For AWS Lambda usage, ensure your secrets are set up as described above.
- The package automatically detects your module system and provides the appropriate format (ESM or CommonJS).
- The
getDecodedJwtTokenfunction only decodes the JWT without validation - usevalidateTokenfor secure token validation.
