iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔐

Implementing JWT Authentication with NestJS and AWS Cognito

に公開

When searching for NestJS and JWT authentication, most results involve cases where you issue the JWT yourself. Since there were few authentication samples where external services like Cognito issue the token, I am sharing this.

The official documentation page regarding authentication can be found at the following link:
https://docs.nestjs.com/security/authentication

Goal

We will add JWT authentication to the app controller as shown below. The specification is that even if a request is sent to this controller, it will be rejected with a 401 error unless a valid JWT is provided in the Authorization header.

app.controller.ts
@UseGuards(JwtGuard)
@Controller()
export class AppController {

  @Get('hello')
  testGet(): string {
    return 'Hello!';
  }
}

Installation

First, please install the following:

 $ npm install --save @nestjs/passport passport jwks-rsa passport-jwt
 $ npm install --save-dev @types/passport-jwt

@nestjs/passport is for handling the Passport module in NestJS.
jwks-rsa is used to retrieve keys from the Cognito server and verify if the signature is correct. Since this can be implemented manually, I will introduce a method that doesn't use this library later.
passport-jwt is used to create the JWT strategy.

What to build

There are mainly three things to create this time:

  • JWT Guard
  • JWT Strategy compatible with Passport
  • Auth Module

If you are not familiar with Guards in NestJS, I recommend reading the explanation on the official website:
https://docs.nestjs.com/guards

The directory structure is as follows:

.
├──app.module.ts
├──app.controller.ts
└──auth
   ├──auth.module.ts
   ├──guard
   │  └──jwt.guard.ts
   └──strategy
      └──jwt.strategy.ts

I will explain each one step by step.

app.module.ts

This is the root module. In this case, there is no specific code for JWT authentication.

app.module.ts
import {
  Module,
  NestModule,
  MiddlewareConsumer,
  RequestMethod,
} from '@nestjs/common';

import { AuthModule } from './auth/auth.module';
import { AppController } from './app.controller';

@Module({
  imports: [AuthModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

app.controller.ts

This is the root controller. We will add JWT authentication to this controller.

app.controller.ts
import {
  Controller,
  Get,
  UseGuards,
} from '@nestjs/common';
import { JwtGuard } from './auth/guard/jwt.guard';

// Apply JWT authentication to this entire controller
@UseGuards(JwtGuard)
@Controller()
export class AppController {

  @Get('hello')
  testGet(): string {
    return 'Hello!';
  }
}

auth/auth.module.ts

Finally, the main part: the auth module. We will use @nestjs/passport, which is a version of Passport.js (a popular authentication library for Node.js) customized for NestJS.

auth.module.ts
import { Module } from '@nestjs/common';
import { PassportModule } from '@nestjs/passport';

import { JwtStrategy } from './strategy/jwt.strategy';
// Comment in if you want to use Pattern 2.
// import { ManualJwtStrategy } from './strategy/jwt.manual.strategy';

@Module({
  imports: [
    PassportModule.register({ defaultStrategy: 'jwt' }),
  ],
  providers: [
    JwtStrategy,
    // ManualJwtStrategy 
  ],
})
export class AuthModule {}

auth/guard/jwt.guard.ts

We will create a NestJS Guard for JWT. By using it with the @UseGuards decorator in a controller, you can reject invalid authentication requests.

auth/guard/jwt.guard.ts
import { AuthGuard } from '@nestjs/passport';

// The value of the argument for AuthGuard('jwt')
// must match PassportStrategy(Strategy, 'jwt') in jwt.strategy.ts.
export class JwtGuard extends AuthGuard('jwt') {
  constructor() {
    super();
  }
}

[Pattern 1: Verification with Library] auth/strategy/jwt.strategy.ts

This is the core of JWT authentication. The Strategy from passport-jwt checks the JWT based on the secretOrKeyProvider specified in the constructor. It decodes and passes only valid JWTs to the validate method. Invalid JWTs will return a 401 error at that point.

One tricky thing is that it doesn't leave detailed logs explaining why a 401 error occurred, so you don't know if the token is invalid or if there's an issue with another part of the implementation. In such cases, implementing it using Pattern 2 (described below) might make debugging easier.

auth/strategy/jwt.strategy.ts
import {
  Injectable,
  Logger,
} from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { passportJwtSecret } from 'jwks-rsa';
import { ExtractJwt, Strategy } from 'passport-jwt';

export interface Claim {
  sub: string;
  email: string;
  token_use: string;
  auth_time: number;
  iss: string;
  exp: number;
  username: string;
  client_id: string;
}

const COGNITO_CLIENT_ID = 'hogehoge';
const COGNITO_REGION = 'ap-northeast-1';
const COGNITO_USERPOOL_ID = 'fugafuga';

const AUTHORITY = `https://cognito-idp.${COGNITO_REGION}.amazonaws.com/${COGNITO_USERPOOL_ID}`;

// The first argument of the PassportStrategy(Strategy, 'jwt') part
// must match AuthGuard('jwt') in jwt.guard.ts.
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  private logger = new Logger(JwtStrategy.name);

  constructor() {
    super({
      // Get Bearer token from the header
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      // Specify the Cognito client ID
      audience: COGNITO_CLIENT_ID,
      // JWT issuer. In this case, Cognito
      issuer: AUTHORITY,
      algorithms: ['RS256'],
      // If you are issuing the JWT yourself, specify the private key,
      // but if an external service like Cognito is issuing it, use secretOrKeyProvider.
      secretOrKeyProvider: passportJwtSecret({
        // Cache the public key. If this is false, you'll need to fetch
        // the public key via HTTP request for every request.
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `${AUTHORITY}/.well-known/jwks.json`,
      }),
      // passReqToCallback: true, // Setting this to true allows using Request as the first argument of validate.
    });
  }

  // After JWT verification, it passes the decoded payload.
  // Note that this is executed after verification. If the JWT is invalid, it won't be executed at all.
  // validate itself can also return a Promise.
  public validate(payload: Claim): string {
    return payload.email;
  }
}

[Pattern 2: Manual Verification] auth/strategy/jwt.strategy.manual.ts

This is a method to perform JWT verification manually without relying on the library's built-in functions.

First, please install the following:

 $ npm install --save passport-custom jwk-to-pem jsonwebtoken
 $ npm install --save-dev @types/jsonwebtoken @types/jwk-to-pem
auth/strategy/jwt.strategy.manual.ts
import {
  UnauthorizedException,
  Injectable,
  Logger,
} from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Request } from 'express';
import { Strategy } from 'passport-custom'; // Note: This is not passport-jwt!

import { handler } from './jwt.verify';

// If you want to use this,
// change AuthGuard('jwt') in jwt.guard.ts
// to AuthGuard('manualJwt').
@Injectable()
export class ManualJwtStrategy extends PassportStrategy(Strategy, 'manualJwt') {
  private logger = new Logger(ManualJwtStrategy.name);

  constructor() {
    super();
  }

  public async validate(req: Request): Promise<string> {
    const info = await handler(req.get('Authorization'));
    if (!info.isValid) throw new UnauthorizedException(info.error);

    return info.email;
  }
}

We will manually handle what the Strategy from 'passport-jwt' was doing for us. What it does is:

  1. Retrieve the token from the request's Authorization header. At that time, perform a simple validation based on character count.
  2. Retrieve the public key from the Cognito server.
  3. Verify if the JWT signature is correct using the public key.
  4. If it's incorrect, return the error details.
  5. If it's correct, return the decoded content.

That's it. I referred to code from some article, but I've forgotten the source.

Also, I found this library after I wrote this...
https://github.com/awslabs/aws-jwt-verify

auth/strategy/jwt.verify.ts
/* eslint-disable camelcase */
import { UnauthorizedException, Logger } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import jwkToPem from 'jwk-to-pem';
import request from 'request';

const logger = new Logger('jwt.verify');

// Reference: https://github.com/awslabs/aws-support-tools/blob/master/Cognito/decode-verify-jwt/decode-verify-jwt.ts

const TOKEN_USE_ACCESS = 'access';
const TOKEN_USE_ID = 'id';

const ALLOWED_TOKEN_USES = [TOKEN_USE_ACCESS, TOKEN_USE_ID];
const ISSUER = `https://cognito-idp.${process.env.AWS_REGION}.amazonaws.com/${process.env.COGNITO_USER_POOL_ID}`;

export interface ClaimVerifyRequest {
  readonly token?: string;
}

export interface ClaimVerifyResult {
  readonly email: string;
  readonly clientId: string;
  readonly isValid: boolean;
  readonly error?: any;
}

interface TokenHeader {
  kid: string;
  alg: string;
}
interface PublicKey {
  alg: string;
  e: string;
  kid: string;
  kty: 'RSA'; // The sample used string, but I changed it because it was rejected by the jwkToPem type
  n: string;
  use: string;
}
interface PublicKeyMeta {
  instance: PublicKey;
  pem: string;
}

interface PublicKeys {
  keys: PublicKey[];
}

interface MapOfKidToPublicKey {
  [key: string]: PublicKeyMeta;
}

export interface Claim {
  sub: string;
  email: string;
  token_use: string;
  auth_time: number;
  iss: string;
  exp: number;
  username: string;
  client_id: string;
  'cognito:username': string;
}

/** Response example
"sub": "aaaaaaaa-bbbb-cccc-dddd-example",
"aud": "xxxxxxxxxxxxexample",
"email_verified": true,
"token_use": "id",
"auth_time": 1500009400,
"iss": "https://cognito-idp.ap-northeast-1.amazonaws.com/your_userpool_id",
"cognito:username": "HATOSUKE",
"exp": 1500013000,
"given_name": "HATOSUKE",
"iat": 1500009400,
"email": "test@example.com"
*/

let cacheKeys: MapOfKidToPublicKey | undefined;
// One time initialisation to download the JWK keys and convert to PEM format. Returns a promise.
const getPublicKeys = async (): Promise<MapOfKidToPublicKey> => {
  if (!cacheKeys) {
    const options = {
      url: `${ISSUER}/.well-known/jwks.json`,
      json: true,
    };
    const publicKeys = await new Promise<PublicKeys>((resolve, reject) => {
      request.get(options, function (err, resp, body: PublicKeys) {
        if (err) {
          logger.debug(`Failed to download JWKS data. err: ${err}`);
          reject(new Error('Internal debug occurred downloading JWKS data.')); // don't return detailed info to the caller

          return;
        }
        if (!body || !body.keys) {
          logger.debug(
            `JWKS data is not in expected format. Response was: ${JSON.stringify(
              resp,
            )}`,
          );
          reject(new Error('Internal debug occurred downloading JWKS data.')); // don't return detailed info to the caller

          return;
        }

        resolve(body);
      });
    });

    cacheKeys = publicKeys.keys.reduce((agg, current) => {
      const pem = jwkToPem(current);
      agg[current.kid] = { instance: current, pem };

      return agg;
    }, {} as MapOfKidToPublicKey);

    return cacheKeys;
  }

  return cacheKeys;
};

// Verify the Authorization header and return a promise.
function verifyProm(keys: MapOfKidToPublicKey, token?: string): Promise<Claim> {
  return new Promise((resolve, reject) => {
    // Decode the JWT token so we can match it to a key to verify it against

    if (!token || token.length < 2) {
      reject(
        new UnauthorizedException(
          "Invalid or missing Authorization header. Expected to be in the format 'Bearer <your_JWT_token>'.",
        ),
      );

      return;
    }

    const decodedNotVerified = jwt.decode(token, {
      complete: true,
    }) as { header: TokenHeader } | null;

    if (!decodedNotVerified) {
      logger.debug('Invalid JWT token. jwt.decode() failure.');
      reject(
        new UnauthorizedException(
          'Authorization header contains an invalid JWT token.',
        ),
      ); // don't return detailed info to the caller

      return;
    }

    if (
      !decodedNotVerified.header.kid ||
      !keys[decodedNotVerified.header.kid]
    ) {
      logger.debug(
        `Invalid JWT token. Expected a known KID ${JSON.stringify(
          Object.keys(keys),
        )} but found ${decodedNotVerified.header.kid}.`,
      );
      reject(
        new UnauthorizedException(
          'Authorization header contains an invalid JWT token.',
        ),
      ); // don't return detailed info to the caller

      return;
    }

    const key = keys[decodedNotVerified.header.kid];

    // Now verify the JWT signature matches the relevant key
    jwt.verify(
      token,
      key.pem,
      {
        issuer: ISSUER,
      },
      function (err, decodedAndVerified: any) {
        if (err) {
          logger.debug(`Invalid JWT token. jwt.verify() failed: ${err}.`);
          if (err instanceof jwt.TokenExpiredError) {
            reject(
              new UnauthorizedException(
                `Authorization header contains a JWT token that expired at ${err.expiredAt.toISOString()}.`,
              ),
            );
          } else {
            reject(
              new UnauthorizedException(
                'Authorization header contains an invalid JWT token.',
              ),
            ); // don't return detailed info to the caller
          }

          return;
        }

        // The signature matches so we know the JWT token came from our Cognito instance, now just verify the remaining claims in the token

        // Verify the token_use matches what we've been configured to allow
        if (ALLOWED_TOKEN_USES.indexOf(decodedAndVerified.token_use) === -1) {
          logger.debug(
            `Invalid JWT token. Expected token_use to be ${JSON.stringify(
              ALLOWED_TOKEN_USES,
            )} but found ${decodedAndVerified.token_use}.`,
          );
          reject(
            new UnauthorizedException(
              'Authorization header contains an invalid JWT token.',
            ),
          ); // don't return detailed info to the caller

          return;
        }

        // Verify the client id matches what we expect. Will be in either the aud or the client_id claim depending on whether it's an id or access token.
        const clientId = decodedAndVerified.aud || decodedAndVerified.client_id;
        if (clientId !== process.env.COGNITO_CLIENT_ID) {
          logger.debug(
            `Invalid JWT token. Expected client id to be ${process.env.COGNITO_CLIENT_ID} but found ${clientId}.`,
          );
          reject(
            new UnauthorizedException(
              'Authorization header contains an invalid JWT token.',
            ),
          ); // don't return detailed info to the caller

          return;
        }

        // Done - all JWT token claims can now be trusted
        resolve(decodedAndVerified as Claim);
      },
    );
  });
}

// Verify the Authorization header and call the next middleware handler if appropriate
function verifyMiddleWare(
  pemsDownloadProm: Promise<MapOfKidToPublicKey>,
  token?: string,
) {
  return pemsDownloadProm
    .then((keys) => {
      return verifyProm(keys, token);
    })
    .then((decoded: Claim) => {
      // Caller is authorised - copy some useful attributes into the req object for later use
      logger.debug(`Valid JWT token. Decoded: ${JSON.stringify(decoded)}.`);

      return {
        email: decoded.email,
        clientId: decoded.client_id,
        isValid: true,
      };
    })
    .catch((err: any) => {
      logger.debug(String(err));

      return { email: '', clientId: '', error: err, isValid: false };
    });
}

// Get the middleware function that will verify the incoming request
const handler = async (auth?: string): Promise<ClaimVerifyResult> => {
  // Fetch the JWKS data used to verify the signature of incoming JWT tokens

  // Check the format of the auth header string and break out the JWT token part
  if (!auth || auth.length < 10) {
    throw new UnauthorizedException(
      "Invalid or missing Authorization header. Expected to be in the format 'Bearer <your_JWT_token>'.",
    );
  }

  const authPrefix = auth.substring(0, 7).toLowerCase();
  if (authPrefix !== 'bearer ') {
    throw new UnauthorizedException(
      "Authorization header is expected to be in the format 'Bearer <your_JWT_token>'.",
    );
  }

  const token = auth.substring(7);

  const pemsDownloadProm = getPublicKeys().catch((err) => {
    // Failed to get the JWKS data - all subsequent auth requests will fail
    logger.debug(err);

    return { err };
  });

  return verifyMiddleWare(pemsDownloadProm, token);
};

export { handler };

Discussion