Created
January 30, 2021 14:32
-
-
Save revant/4d3ab418cafbe3d8fb918706fdb9c082 to your computer and use it in GitHub Desktop.
IdTokenGuard NestJS Guard to verify IdToken using JWKS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; | |
| import { GqlExecutionContext } from '@nestjs/graphql'; | |
| import * as jwt from 'jsonwebtoken'; | |
| import * as jwksClient from 'jwks-rsa'; | |
| @Injectable() | |
| export class IdTokenGuard implements CanActivate { | |
| canActivate(context: ExecutionContext) { | |
| const ctx = GqlExecutionContext.create(context); | |
| const req = ctx.getContext().req; | |
| const idToken = this.getIdToken(req); | |
| return new Promise<boolean>((resolve) => { | |
| jwt.verify(idToken, this.getKey.bind(this), (err, decoded) => { | |
| if (err) { | |
| return resolve(false); | |
| } | |
| req.idToken = decoded; | |
| /** | |
| * req.idToken has role and profile info | |
| req.idToken = { | |
| iss: 'https://accounts.example.com', | |
| aud: '4d8a2148-4830-431a-bf83-540eeee860c0', | |
| iat: 1612014707, | |
| exp: 1612018307, | |
| sub: '630305be-6ddc-4767-8300-11ef92488cf4', | |
| nonce: 'NU9uR2ZZbTZUTk8zN28xaUxXNlR4UGVVbVY0LjJGUkprTHJheVNoTFlQfnpM', | |
| roles: [ | |
| 'administrator', | |
| 'manager', | |
| ], | |
| at_hash: 'BXQEQj-ffS9IndaXUF8osw' | |
| } | |
| */ | |
| return resolve(true); | |
| }); | |
| }); | |
| } | |
| getIdToken(request) { | |
| if (!request?.headers?.authorization) { | |
| return null; | |
| } | |
| return request?.headers?.authorization | |
| ? request.headers.authorization.split(' ')[1] | |
| : null; | |
| } | |
| getKey(header, callback) { | |
| const client = jwksClient({ | |
| // JWKS_ENDPOINT=https://accounts.example.com/.well-known/jwks | |
| jwksUri: process.env.JWKS_ENDPOINT, | |
| }); | |
| client.getSigningKey(header.kid, (err, key) => { | |
| if (err) { | |
| return callback(err); | |
| } | |
| const signingKey = key.getPublicKey(); | |
| if (signingKey) { | |
| return callback(null, signingKey); | |
| } | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment