Skip to content

Use JWKS to validate incoming JWT auth tokens #57

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"csv-stringify": "^6.5.2",
"dotenv": "^16.5.0",
"jsonwebtoken": "^9.0.2",
"jwks-rsa": "^3.2.0",
"lodash": "^4.17.21",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
Expand Down
87 changes: 87 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions src/config/config.env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,6 @@ export class ConfigEnv {
@IsString()
AUTH0_M2M_GRANT_TYPE!: string;

@IsString()
AUTH0_CERT!: string;

@IsString()
AUTH0_CLIENT_ID!: string;

Expand Down
52 changes: 52 additions & 0 deletions src/core/auth/jwt.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { Logger } from '@nestjs/common';
import { decode } from 'jsonwebtoken';
import { JwksClient } from 'jwks-rsa';
import { ENV_CONFIG } from 'src/config';

const logger = new Logger(`auth/jwks`);

const client = new JwksClient({
jwksUri: `${ENV_CONFIG.AUTH0_M2M_TOKEN_URL}/.well-known/jwks.json`,
cache: true,
rateLimit: true,
});

/**
* Retrieves the signing key for a given JWT token.
*
* This function decodes the token to extract its header and uses the `kid` (Key ID)
* to fetch the corresponding signing key from a remote client. The signing key is
* then resolved as a public key.
*
* @param token - The JWT token for which the signing key is to be retrieved.
* @returns A promise that resolves with the public signing key as a string.
* @throws An error if the token is invalid, the `kid` is missing, or the signing key
* cannot be retrieved or resolved.
*/
export const getSigningKey = (token: string) => {
const tokenHeader = decode(token, { complete: true })?.header;

return new Promise((resolve, reject) => {
if (!tokenHeader || !tokenHeader.kid) {
logger.error('Invalid token: Missing key ID');
return reject(new Error('Invalid token: Missing key ID'));
}

client.getSigningKey(tokenHeader.kid, function (err, key) {
if (err || !key) {
logger.error('Error getting signing key:', err);
return reject(new Error('Invalid token: Unable to get signing key'));
}

// Get the public key using the proper method
const signingKey = key.getPublicKey();

if (!signingKey) {
logger.error('Error getting public key!');
return reject(new Error('Invalid token: Unable to get public key'));
}

resolve(signingKey);
});
});
};
6 changes: 4 additions & 2 deletions src/core/auth/middleware/tokenValidator.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import {
} from '@nestjs/common';
import * as jwt from 'jsonwebtoken';
import { ENV_CONFIG } from 'src/config';
import { getSigningKey } from '../jwt';

const logger = new Logger(`Auth/TokenValidatorMiddleware`);

@Injectable()
export class TokenValidatorMiddleware implements NestMiddleware {
use(req: any, res: Response, next: (error?: any) => void) {
async use(req: any, res: Response, next: (error?: any) => void) {
const [type, idToken] = req.headers.authorization?.split(' ') ?? [];

if (type !== 'Bearer' || !idToken) {
Expand All @@ -20,7 +21,8 @@ export class TokenValidatorMiddleware implements NestMiddleware {

let decoded: any;
try {
decoded = jwt.verify(idToken, ENV_CONFIG.AUTH0_CERT);
const signingKey = await getSigningKey(idToken);
decoded = jwt.verify(idToken, signingKey);
} catch (error) {
logger.error('Error verifying JWT', error);
throw new UnauthorizedException('Invalid or expired JWT!');
Expand Down