iTranslated by AI
Becoming a Master of Strategies in NestJS
Introduction
Previously, I wrote an article on implementing authentication based on the NestJS documentation.
While that approach works, there is a very useful module called Passport. It allows you to perform a wide variety of validations, making it extremely helpful.
In this article, I will learn how to use the Passport module in NestJS based on the official documentation, explore the internal structure of the Passport module, and finally customize it.
This turned into quite a long article before I knew it, but I hope you will read through it.
Learning Authentication in NestJS Using Passport from the Documentation
Introduction
The Passport module has many strategies and supports various authentication methods. However, there are so many of them that it can be confusing to know which one to use. That is why @nestjs/passport exists, allowing you to automatically select strategies compatible with NestJS.
The documentation covers how to use the Passport module in conjunction with @nestjs/passport.
Requirements from the Documentation
In the documentation, we will implement the following features:
- Authentication with username/password
- Guarding username/password authentication
- JWT issuance after authentication
- Validation of JWTs present in the Authorization Header
- Guarding JWT validation
Note that the modules used for username/password authentication, JWT issuance, and JWT validation differ slightly. We will look at each detail, but generally, username/password authentication uses features around thepassport-localmodule, JWT issuance uses@nestjs/jwt, and JWT validation usespassport-jwt.
Each feature is not necessarily tightly coupled, so you can choose to apply only the JWT validation part to your project. Therefore, it is better to consider the chapters "Implementing Passport local", "JWT functionality", and "Implementing Passport JWT" as independent to get a better overview of the documentation. Now that we have a light overview of the requirements and the structure, let's start by implementing username/password authentication.
Username/Password Authentication and Guarding with passport-local
Before using passport-local, we need a dummy login process, so please create the following code files:
users/users.service.ts
import { Injectable } from "@nestjs/common";
// This should be a real class/interface representing a user entity
export type User = any;
@Injectable()
export class UsersService {
private readonly users = [
{
userId: 1,
username: "john",
password: "changeme",
},
{
userId: 2,
username: "maria",
password: "guess",
},
];
async findOne(username: string): Promise<User | undefined> {
return this.users.find((user) => user.username === username);
}
}
users/users.module.ts
import { Module } from "@nestjs/common";
import { UsersService } from "./users.service";
@Module({
providers: [UsersService],
exports: [UsersService],
})
export class UsersModule {}
auth/auth.service.ts
import { Injectable } from "@nestjs/common";
import { UsersService } from "../users/users.service";
@Injectable()
export class AuthService {
constructor(private usersService: UsersService) {}
async validateUser(username: string, pass: string): Promise<any> {
const user = await this.usersService.findOne(username);
if (user && user.password === pass) {
const { password, ...result } = user;
return result;
}
return null;
}
}
auth/auth.module.ts
import { Module } from "@nestjs/common";
import { AuthService } from "./auth.service";
import { UsersModule } from "../users/users.module";
@Module({
imports: [UsersModule],
providers: [AuthService],
})
export class AuthModule {}
Now that the preparations are done, let's use passport-local. First, install the necessary modules using the following command:
$ npm install --save @nestjs/passport passport passport-local
$ npm install --save-dev @types/passport-local
While the actual functionality used is from passport-local, the passport module is required to invoke it, and @nestjs/passport makes it easy to use the passport module in NestJS. That is why we are importing three modules in total.
By the way, as I mentioned earlier, the chapters "Implementing Passport local", "JWT functionality", and "Implementing Passport JWT" can be considered independent, but the discussion assumes the previously installed modules are available. Therefore, if you are only looking at each chapter, please be aware that the following module installations are required for each:
- Username/Password Authentication and Guarding
- dependencies:
@nestjs/passport,passport,passport-local - devDependencies:
@types/passport-local
- dependencies:
- JWT Issuance
- dependencies:
@nestjs/jwt
- dependencies:
- JWT Validation and Guarding
- dependencies:
@nestjs/passport,passport,passport-jwt - devDependencies:
@types/passport-jwt
- dependencies:
Once installed, create local.strategy.ts under the auth folder and add the following code: (The folder location and filename can be anything.)
import { Strategy } from "passport-local";
import { PassportStrategy } from "@nestjs/passport";
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { AuthService } from "./auth.service";
@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
constructor(private authService: AuthService) {
super();
}
async validate(username: string, password: string): Promise<any> {
const user = await this.authService.validateUser(username, password);
if (!user) {
throw new UnauthorizedException();
}
return user;
}
}
The code above checks if the username and password exist in the request body or query, and if they do, it verifies if a matching user exists using the validateUser method. If it does not exist, it throws a 401 error; if it does, it returns the retrieved value. This is the general flow when creating a class to perform some form of validation using the Passport module:
- Call the
PassportStrategyfunction with the strategy you want to use as an argument. - Extend this class.
- Execute the parent constructor in the constructor.
- Implement the
validatemethod to handle your custom validation logic.
Inheriting via extends (Step 2) is mandatory because the PassportStrategy function returns an abstract class. We will look into the details of the PassportStrategy function later, but for now, please understand that you must extend it because it returns an abstract class. Executing the parent constructor (Step 3) is also mandatory to store the necessary values for the strategy you are using. We will also look at the strategy code details for JwtStrategy later, so for now, please understand that you must call the parent constructor to make the strategy runnable. Finally, the validate method (Step 4) is a custom method executed after the strategy's validation is complete. You can perform validations like checking against your own database here. As a note, you must define this method and return some value even if you don't have custom validation logic. The reason for the necessity of the validate method is due to the abstract class returned by the PassportStrategy function:
export function PassportStrategy<T extends Type<any> = any>(
Strategy: T,
name?: string | undefined,
callbackArity?: true | number
): {
new (...args): InstanceType<T>;
} {
abstract class MixinStrategy extends Strategy {
abstract validate(...args: any[]): any;
//...omitted
}
return MixinStrategy;
}
The MixinStrategy class returned by the PassportStrategy function defines the validate method as abstract. Therefore, subsequent processes expect the validate method to exist, and errors will occur if it is missing. This is why you must implement the validate method. As for the reason why the validate method must return a value, it is due to the Guard logic that uses the class created:
function createAuthGuard(type?: string | string[]): Type<IAuthGuard> {
class MixinAuthGuard<TUser = any> implements CanActivate {
//...omitted
async canActivate(context: ExecutionContext): Promise<boolean> {
const options = {
...defaultOptions,
...this.options,
...(await this.getAuthenticateOptions(context))
};
//...omitted
request[options.property || defaultOptions.property] = user;
return true;
}
//...omitted
}
What I want you to focus on is request[options.property || defaultOptions.property] = user;. The user assigned to the request object is the return value set in the validate method. We will have an opportunity to touch on why this is the case later in "Looking at what AuthGuard does", so please accept this as how it works for now. Since the return value of the validate method is assigned to the Request object in this way, if the validate method returns nothing, subsequent processing will not work correctly. Therefore, please ensure that the validate method returns some value. You might still have questions about how to know the arguments for the validate method. This can be traced from this site. The site provides a list of strategies provided by Passport. From there, navigate to the details page of the strategy you want to use and check the sample code when instantiating the strategy. The arguments of the callback function other than done in the function defined there are the arguments received by the validate method. Since words alone can be confusing, let's look at passport-local used this time. Checking the usage of passport-local reveals the following code:
passport.use(
new LocalStrategy(function (username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false);
}
if (!user.verifyPassword(password)) {
return done(null, false);
}
return done(null, user);
});
})
);
The focus is on the function(username, password, done) part. This function is set when instantiating LocalStrategy, and it contains username and password besides the done argument. These arguments are passed to the validate method. I will not explain why this is the case in this article, but since the relevant code parts for the reason should appear in "Looking at what PassportStrategy's super() does" and "Looking at what AuthGuard does", I hope you can deduce it from there. (Sorry, I didn't have the energy to explain this far.)
Now that the implementation of the class using passport-local is complete, let's edit auth/auth.module.ts to make it usable:
import { Module } from "@nestjs/common";
import { AuthService } from "./auth.service";
import { UsersModule } from "../users/users.module";
import { PassportModule } from "@nestjs/passport";
import { LocalStrategy } from "./local.strategy";
@Module({
imports: [UsersModule, PassportModule],
providers: [AuthService, LocalStrategy],
})
export class AuthModule {}
Since we are using the PassportStrategy function, we import the @nestjs/passport module and add the LocalStrategy class created in another file to providers so it can be used. Now that we are ready to perform username/password authentication, let's create the endpoint. Change app.controller.ts as follows:
import { Controller, Request, Post, UseGuards } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Controller()
export class AppController {
@UseGuards(AuthGuard("local"))
@Post("auth/login")
async login(@Request() req) {
return req.user;
}
}
Using the AuthGuard function provided by the @nestjs/passport module allows the LocalStrategy class we created earlier to be executed as a guard. Note that the value set to the AuthGuard function is the string "local", not the LocalStrategy class. This appears suddenly and may be confusing, but basically, if you use a strategy provided by passport-local, this value will be "local". By the way, you can specify an arbitrary name in the second argument of the PassportStrategy function, and if you set a name there, that name will be the value used when calling the AuthGuard function. I have explained this later in "What is the string when calling AuthGuard?", so I will leave the explanation here. The authentication endpoint is now created. While I'd like to verify it, the current setup has no extensibility for the guard. Therefore, add the following code to an arbitrary location (in this case, auth/local-auth.guard.ts):
import { Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Injectable()
export class LocalAuthGuard extends AuthGuard("local") {}
Although not implemented here, once defined like this, you can set various methods within the class. Doing it this way helps prevent typos during invocation, which is why NestJS also recommends it. Now that the file for the guard is created, correct the endpoint created earlier:
import { Controller, Request, Post, UseGuards } from "@nestjs/common";
import { LocalAuthGuard } from "./auth/local-auth.guard";
import { AuthService } from "./auth/auth.service";
@Controller()
export class AppController {
constructor(private authService: AuthService) {}
@UseGuards(LocalAuthGuard)
@Post("auth/login")
async login(@Request() req) {
return req.user;
}
}
Now, start NestJS and try executing each of the following curl commands:
curl -X POST http://localhost:3000/auth/login -d '{"username": "notExistUser", "password": "notExistPass"}' -H "Content-Type: application/json"
curl -X POST http://localhost:3000/auth/login -d '{"username": "john", "password": "changeme"}' -H "Content-Type: application/json"
I expect the first curl command to return a 401 error, and the second one to return user information. This completes the requirements "① Authentication with username/password" and "② Guarding username/password authentication".
JWT Issuance
From here, we will issue a JWT upon successful authentication and return it. I have already explained the specific details in "Revisiting NestJS Authentication Documentation", so I will not include them here. However, since the signIn method in that article performs user validation, that part is no longer needed. Therefore, I have separately performed the task of changing the signIn method to a login method as shown below:
async login(user: any) {
const payload = { username: user.username, sub: user.userId };
return {
access_token: this.jwtService.sign(payload),
};
}
Now, let's describe the process after the preparations for JWT issuance are complete. You simply need to change the login method in app.controller.ts as shown below, inject AuthService into the constructor, and add exports: [AuthService], to auth/auth.module.ts.
async login(@Request() req) {
return this.authService.login(req.user);
}
Run the following command: curl -X POST http://localhost:3000/auth/login -d '{"username": "john", "password": "changeme"}' -H "Content-Type: application/json". If you confirm that a value like the one below is returned, "③ JWT issuance after authentication" is complete.
{"access_token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImpvaG4iLCJzdWIiOjEsImlhdCI6MTcwMDcxMzY0OCwiZXhwIjoxNzAwNzEzNzA4fQ.ReYiju2HisO8WTANNdI6Fg9vcqwz4SsIHFl4W8_RY7k"}
JWT Verification and Guarding
Now that authentication and JWT issuance are complete, we will create code to verify whether the JWT has been properly signed, and create a guard based on that. First, execute the following command to import the necessary modules:
$ npm install --save passport-jwt
$ npm install --save-dev @types/passport-jwt
Next, implement the following code in an arbitrary file (in this case, auth/jwt.strategy.ts):
import { ExtractJwt, Strategy } from "passport-jwt";
import { PassportStrategy } from "@nestjs/passport";
import { Injectable } from "@nestjs/common";
import { jwtConstants } from "./constants";
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: jwtConstants.secret,
});
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}
The structure and syntax are mostly the same as when using passport-local, but you need to configure the constructor for passport-jwt. Specifically, there are four major settings:
- How to retrieve the JWT
- Key settings for verification
- Settings for values to verify within the JWT
- Configuration of the
validatemethod arguments*
*Technically, this is the configuration of the arguments for the callback function executed after JWT verification in passport-jwt. I am using specific names here to make it easier to visualize.
Categorizing these settings and the specific passport-jwt properties:
- ① Method to retrieve JWT:
jwtFromRequest - ② Key settings for verification:
secretOrKey,secretOrKeyProvider - ③ Settings for values to verify within the JWT:
issuer,audience,algorithms,ignoreExpiration,jsonWebTokenOptions - ④ Configuration of
validatemethod arguments:passReqToCallback
Regarding ④, it can be set to a boolean. According to the documentation:
If true the request will be passed to the verify callback. i.e. verify(request, jwt_payload, done_callback).
In other words, this property determines whether to add the Request object as the first argument of the validate method. If you want to perform operations on the Request object explicitly, setting this to true allows you to handle it in the validate method. We do not need to perform any special operations, so we will not set it.
Since jwtFromRequest and secretOrKey (or secretOrKeyProvider) are the minimum requirements for using passport-jwt, they are included as shown above.
ExtractJwt.fromAuthHeaderAsBearerToken(), which is set for the jwtFromRequest property, is a method used to retrieve the Bearer token from the Authorization Header. There are various other methods available, so if you are interested, check this file.
The secretOrKey property requires the key information to be passed as a String or Buffer. Since we created a temporary key as a string during JWT issuance, we are importing it.
Once this is done, the rest is the same as with passport-local. Pass JwtStrategy to auth/auth.module.ts.
import { Module } from "@nestjs/common";
import { AuthService } from "./auth.service";
import { LocalStrategy } from "./local.strategy";
import { JwtStrategy } from "./jwt.strategy";
import { UsersModule } from "../users/users.module";
import { PassportModule } from "@nestjs/passport";
import { JwtModule } from "@nestjs/jwt";
import { jwtConstants } from "./constants";
@Module({
imports: [
UsersModule,
PassportModule,
JwtModule.register({
secret: jwtConstants.secret,
signOptions: { expiresIn: "60s" },
}),
],
providers: [AuthService, LocalStrategy, JwtStrategy],
exports: [AuthService],
})
export class AuthModule {}
After that, create a file to turn JwtStrategy into a guard. Note that when using passport-jwt, the string set for AuthGuard defaults to "jwt".
import { Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt") {}
Finally, create an endpoint in app.controller.ts that applies the newly created guard.
import { Controller, Get, Request, Post, UseGuards } from "@nestjs/common";
import { JwtAuthGuard } from "./auth/jwt-auth.guard";
import { LocalAuthGuard } from "./auth/local-auth.guard";
import { AuthService } from "./auth/auth.service";
@Controller()
export class AppController {
constructor(private authService: AuthService) {}
@UseGuards(LocalAuthGuard)
@Post("auth/login")
async login(@Request() req) {
return this.authService.login(req.user);
}
@UseGuards(JwtAuthGuard)
@Get("profile")
getProfile(@Request() req) {
return req.user;
}
}
Finally, execute the following curl commands to verify the operation.
$ curl http://localhost:3000/profile
$ curl http://localhost:3000/profile -H "Authorization: Bearer aaaa"
$ curl -X POST http://localhost:3000/auth/login -d '{"username": "john", "password": "changeme"}' -H "Content-Type: application/json"
$ curl http://localhost:3000/profile -H "Authorization: Bearer <acquired access token>"
The first command returns a 401 error because there is no access token. The second command also returns a 401 error due to token verification failure, even though the Bearer header is set. Only after acquiring a token with the third command and setting it, the return value containing the user information is returned.
This fulfills all the required requirements. We have explained the general parts handled in the documentation, so from here on, we will look at the internal details of each function.
Examining what super() in PassportStrategy does
Here, we will examine what the following code, which we used when creating JwtStrategy, actually does.
import { Strategy } from 'passport-jwt';
//...omitted
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: //...omitted,
secretOrKeyProvider: //...omitted
});
}
async validate(payload: any) {
//...omitted
}
}
We specifically want to look at the following points:
① What the parent constructor called inside the constructor does.
② The contents of the jwtFromRequest property.
③ The contents of the secretOrKeyProvider property.
Let's take a look in order.
① Confirming what the parent constructor does
The PassportStrategy function
First, let's look at the internals of PassportStrategy, which is the target of super.
export function PassportStrategy<T extends Type<any> = any>(
Strategy: T,
name?: string | undefined,
callbackArity?: true | number
): {
new (...args): InstanceType<T>;
} {
abstract class MixinStrategy extends Strategy {
abstract validate(...args: any[]): any;
constructor(...args: any[]) {
const callback = async (...params: any[]) => {
const done = params[params.length - 1];
try {
const validateResult = await this.validate(...params);
if (Array.isArray(validateResult)) {
done(null, ...validateResult);
} else {
done(null, validateResult);
}
} catch (err) {
done(err, null);
}
};
if (callbackArity !== undefined) {
const validate = new.target?.prototype?.validate;
const arity =
callbackArity === true ? validate.length + 1 : callbackArity;
if (validate) {
Object.defineProperty(callback, "length", {
value: arity,
});
}
}
super(...args, callback);
const passportInstance = this.getPassportInstance();
if (name) {
passportInstance.use(name, this as any);
} else {
passportInstance.use(this as any);
}
}
getPassportInstance() {
return passport;
}
}
return MixinStrategy;
}
The main tasks performed here can be categorized into four points:
① Create and return a class that extends the Strategy argument.
② Create a function that executes the validate method.
③ Pass the options set in the constructor of the Strategy argument and the function from ② to the super constructor.
④ Use the use method of the passport module to pass the created class.
From these points, we can understand that PassportStrategy itself is a function that returns a class, which is why we can write class JwtStrategy extends PassportStrategy(Strategy). Since PassportStrategy returns an abstract class that assumes a validate method exists, we can understand why the validate method is required when using it.
Since it also calls the constructor of the Strategy argument, we can infer that this PassportStrategy function acts as a bridge connecting NestJS and the functionality of the Strategy argument. It can also be considered a bridge to the passport module.
Now that we have a rough grasp of the role of the PassportStrategy function, we will proceed to look at the contents of the Strategy argument and what passport.use is doing.
The role of the Strategy argument
If we re-examine the JwtStrategy we created initially, we can see that the passport-jwt module Strategy is set as the Strategy argument of the PassportStrategy function.
import { Strategy } from 'passport-jwt';
//...omitted
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor() {
super({
jwtFromRequest: //...omitted,
secretOrKeyProvider: //...omitted
});
}
async validate(payload:any){
//...omitted
}
}
Therefore, looking at the actual Strategy, it looks like this:
function JwtStrategy(options, verify) {
passport.Strategy.call(this);
this.name = "jwt";
this._secretOrKeyProvider = options.secretOrKeyProvider;
if (options.secretOrKey) {
if (this._secretOrKeyProvider) {
throw new TypeError(
"JwtStrategy has been given both a secretOrKey and a secretOrKeyProvider"
);
}
this._secretOrKeyProvider = function (request, rawJwtToken, done) {
done(null, options.secretOrKey);
};
}
if (!this._secretOrKeyProvider) {
throw new TypeError("JwtStrategy requires a secret or key");
}
this._verify = verify;
if (!this._verify) {
throw new TypeError("JwtStrategy requires a verify callback");
}
this._jwtFromRequest = options.jwtFromRequest;
if (!this._jwtFromRequest) {
throw new TypeError(
"JwtStrategy requires a function to retrieve jwt from requests (see option jwtFromRequest)"
);
}
this._passReqToCallback = options.passReqToCallback;
var jsonWebTokenOptions = options.jsonWebTokenOptions || {};
//for backwards compatibility, still allowing you to pass
//audience / issuer / algorithms / ignoreExpiration
//on the options.
this._verifOpts = assign({}, jsonWebTokenOptions, {
audience: options.audience,
issuer: options.issuer,
algorithms: options.algorithms,
ignoreExpiration: !!options.ignoreExpiration,
});
}
There are parts here that might look familiar. What is happening here is that the options received as arguments are being assigned to the object's own properties. While you might feel confused that this is written as a function rather than a class, given the subsequent processing, it is effectively treating it like a class constructor. Therefore, it is safe to interpret the JwtStrategy as essentially functioning like the following:
class JwtStrategy {
constructor() {}
}
To return to our main topic, the Strategy argument is JwtStrategy, and within the PassportStrategy function, it is setting the values necessary for subsequent JWT-related operations.
About passport.use
Looking at index.js, the entry point for the passport module, we find the following:
// Module dependencies.
var Passport = require("./authenticator"),
SessionStrategy = require("./strategies/session");
/**
* Export default singleton.
*
* @api public
*/
exports = module.exports = new Passport();
/**
* Expose constructors.
*/
exports.Passport = exports.Authenticator = Passport;
exports.Strategy = require("passport-strategy");
/*
* Expose strategies.
*/
exports.strategies = {};
exports.strategies.SessionStrategy = SessionStrategy;
When importing without specifying properties, it is safe to assume the content of authenticator.js in the same directory is being used. By searching for the use method within lib/authenticator.js, we find the following code:
Authenticator.prototype.use = function (name, strategy) {
if (!strategy) {
strategy = name;
name = strategy.name;
}
if (!name) {
throw new Error("Authentication strategies must have a name");
}
this._strategies[name] = strategy;
return this;
};
What this does is, if a strategy name is explicitly passed as an argument, it sets that name as the key and the strategy as the value. Otherwise, it uses the name property of the strategy as the key. Since it throws an error if no name exists, when using the use method, you must either specify the strategy name explicitly or pass an object that has a name property.
We understand that it stores the value in a property, but what is the purpose of this? In fact, when executing the authenticate method—which we will cover in the chapter related to AuthGuard—there is a process to retrieve the strategy registered in the _strategies property using the specified name. Therefore, unless you register the strategy using this use method in advance, the strategy you wish to call will not exist, and the process will not execute.
From the above, we can see that by calling passport.use within the class created by the PassportStrategy function, we are registering the strategy to be used in advance. Thus far, we have covered what happens inside the PassportStrategy function, which was our starting point. Next, we will look at the roles of the jwtFromRequest and secretOrKeyProvider properties that were configured in the constructor.
Role of the jwtFromRequest Property
As mentioned earlier, the jwtFromRequest property comes from the passport-jwt module. Checking the README of the passport-jwt module, we find the following:
jwtFromRequest(REQUIRED) Function that accepts a request as the only parameter and returns either the JWT as a string or null.
We can see that it is a property to set a function that accepts a Request parameter and returns either a JWT-formatted string or null. While the return value is clear, it raises the question of what the Request parameter refers to. Looking at the type definitions for the passport-jwt module in types/passport-jwt/index.d.ts, we find the following:
export interface JwtFromRequestFunction {
(req: express.Request): string | null;
}
As shown above, the argument is an Express Request object. From this, we understand that the jwtFromRequest property is used to set a function that extracts a JWT-formatted token from the received Express request and returns it.
Role of secretOrKeyProvider
First, checking the content of the secretOrKeyProvider property in the README just like the jwtFromRequest property, we find the following description:
secretOrKeyis a string or buffer containing the secret (symmetric) or PEM-encoded public key (asymmetric) for verifying the token's signature. REQUIRED unlesssecretOrKeyProvideris provided.secretOrKeyProvideris a callback in the formatfunction secretOrKeyProvider(request, rawJwtToken, done), which should calldonewith a secret or PEM-encoded public key (asymmetric) for the given key and request combination.doneaccepts arguments in the formatfunction done(err, secret). Note it is up to the implementer to decode rawJwtToken. REQUIRED unlesssecretOrKeyis provided.
secretOrKey is a property for passing key information to verify the token's signature. On the other hand, secretOrKeyProvider is a property for passing a function that defines a callback to provide the key information used for signature verification as an argument. Either property is required, but please note that having both will cause an error (Reference).
Regarding the distinction between the secretOrKey and secretOrKeyProvider properties: if you have the key string or key file on hand, the secretOrKey property is sufficient. Use the secretOrKeyProvider property when you do not have the key information at hand and need a separate process to retrieve it.
While its role is to configure how key information is provided, there is one caution when using the secretOrKeyProvider property: you must ensure the callback function is called within the defined function. Checking the type definition for the secretOrKeyProvider property in types/passport-jwt/index.d.ts:
export interface SecretOrKeyProvider {
(
request: express.Request,
rawJwtToken: any,
done: (err: any, secretOrKey?: string | Buffer) => void
): void;
}
As shown, there is a callback function in the third argument. Therefore, the function set to the secretOrKeyProvider property must be defined to call the callback, as in the code below:
const secretOrKeyProvider: SecretOrKeyProvider = (
request: express.Request,
rawJwtToken: any,
done: (err: any, secretOrKey?: string | Buffer) => void
) => {
// Add custom implementation here
// This function should retrieve the secret or key from the request and JWT token,
// and call the done callback to return the result.
done(null, "your-secret-or-key");
};
If the callback is not called, subsequent processes will not run when the strategy executes, and validation will never finish. We will see the actual implementation in the AuthGuard section, but for now, please understand that it is a property for setting up how to fetch key information, and that once the process for fetching that key is done, it must pass the key information and execute the callback.
Looking at what AuthGuard does
Here, we will look at how JwtStrategy performs JWT validation through the AuthGuard in the code used to run the strategy we created.
import { Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt") {}
First, looking at the AuthGuard code, it is defined as follows:
export const AuthGuard: (type?: string | string[]) => Type<IAuthGuard> =
memoize(createAuthGuard);
Since the memoize function only handles storing data in an object, we should look at the createAuthGuard function, which is the core logic:
function createAuthGuard(type?: string | string[]): Type<IAuthGuard> {
class MixinAuthGuard<TUser = any> implements CanActivate {
@Optional()
@Inject(AuthModuleOptions)
protected options: AuthModuleOptions = {};
constructor(@Optional() options?: AuthModuleOptions) {
this.options = options ?? this.options;
if (!type && !this.options.defaultStrategy) {
authLogger.error(NO_STRATEGY_ERROR);
}
}
async canActivate(context: ExecutionContext): Promise<boolean> {
const options = {
...defaultOptions,
...this.options,
...(await this.getAuthenticateOptions(context)),
};
const [request, response] = [
this.getRequest(context),
this.getResponse(context),
];
const passportFn = createPassportContext(request, response);
const user = await passportFn(
type || this.options.defaultStrategy,
options,
(err, user, info, status) =>
this.handleRequest(err, user, info, context, status)
);
request[options.property || defaultOptions.property] = user;
return true;
}
getRequest<T = any>(context: ExecutionContext): T {
return context.switchToHttp().getRequest();
}
getResponse<T = any>(context: ExecutionContext): T {
return context.switchToHttp().getResponse();
}
async logIn<TRequest extends { logIn: Function } = any>(
request: TRequest
): Promise<void> {
const user = request[this.options.property || defaultOptions.property];
await new Promise<void>((resolve, reject) =>
request.logIn(user, this.options, (err) =>
err ? reject(err) : resolve()
)
);
}
handleRequest(err, user, info, context, status): TUser {
if (err || !user) {
throw err || new UnauthorizedException();
}
return user;
}
getAuthenticateOptions(
context: ExecutionContext
): Promise<IAuthModuleOptions> | IAuthModuleOptions | undefined {
return undefined;
}
}
const guard = mixin(MixinAuthGuard);
return guard as Type<IAuthGuard>;
}
There is a lot of code, but the goal is to create a class using the CanActivate interface for use as a guard. Since our focus is JWT validation, we only need to look at the canActivate method:
async canActivate(context: ExecutionContext): Promise<boolean> {
const options = {
...defaultOptions,
...this.options,
...(await this.getAuthenticateOptions(context)),
};
const [request, response] = [
this.getRequest(context),
this.getResponse(context)
];
const passportFn = createPassportContext(request, response);
const user = await passportFn(
type || this.options.defaultStrategy,
options,
(err, user, info, status) =>
this.handleRequest(err, user, info, context, status)
);
request[options.property || defaultOptions.property] = user;
return true;
}
Even here, much is written, but we should focus only on the createPassportContext function. The rest is just processing to retrieve values; no validation-related operations seem to be performed there. Looking at the code for the createPassportContext function, it looks like this:
const createPassportContext =
(request, response) => (type, options, callback: Function) =>
new Promise<void>((resolve, reject) =>
passport.authenticate(type, options, (err, user, info, status) => {
try {
request.authInfo = info;
return resolve(callback(err, user, info, status));
} catch (err) {
reject(err);
}
})(request, response, (err) => (err ? reject(err) : resolve()))
);
Here, the authenticate method, which is a process of the passport module, appears. Looking inside, we see the following code:
Authenticator.prototype.authenticate = function (strategy, options, callback) {
return this._framework.authenticate(this, strategy, options, callback);
};
It calls the authenticate method found in the _framework property. Let's check the framework method that sets the _framework property:
Authenticator.prototype.framework = function (fw) {
this._framework = fw;
return this;
};
It stores the function set as the argument as is. Finally, let's check the init method and the Authenticator object that holds each method:
function Authenticator() {
this._key = "passport";
this._strategies = {};
this._serializers = [];
this._deserializers = [];
this._infoTransformers = [];
this._framework = null;
this.init();
}
Authenticator.prototype.init = function () {
this.framework(require("./framework/connect")());
this.use(
new SessionStrategy({ key: this._key }, this.deserializeUser.bind(this))
);
this._sm = new SessionManager(
{ key: this._key },
this.serializeUser.bind(this)
);
};
The init function calls the framework method with the object obtained from lib/framework/connect.js. In other words, the preparation for the processing used in the authenticate method is completed at the moment the init method is executed. And since the init method is defined to be executed within Authenticator(), the execution is completed at the time the passport object is instantiated. Therefore, we should look at lib/framework/connect.js to understand the internal processing of the authenticate method. It imports lib/middleware/authenticate.js and sets it to the authenticate property.
Finally, having identified the correct location, let's look at the contents of lib/middleware/authenticate.js. Since there are parts not directly relevant to this discussion, we will not look at everything, but rather focus on the parts of interest.
First, about the return value. Although it may be confusing, it returns the following authenticate function:
return function authenticate(req, res, next) {
//...omitted
};
Therefore, in the createPassportContext function, we connect it with parentheses because we want to perform subsequent processing after executing the passport module's authenticate method.
Next, let's look at the processing within the following function, where the authenticate function (the return value) is executed:
(function attempt(i) {})(0);
In this function, we focus on the following part:
strategy.authenticate(req, options);
strategy is defined as follows:
var layer = name[i];
// If no more strategies exist in the chain, authentication has failed.
if (!layer) {
return allFailed();
}
// Get the strategy, which will be used as prototype from which to create
// a new instance. Action functions will then be bound to the strategy
// within the context of the HTTP request/response pair.
var strategy, prototype;
if (typeof layer.authenticate == "function") {
strategy = layer;
} else {
prototype = passport._strategy(layer);
if (!prototype) {
return next(new Error('Unknown authentication strategy "' + layer + '"'));
}
strategy = Object.create(prototype);
}
If the layer variable has an authenticate property and it is a function, it is the target object, so it is stored as is. Otherwise, it uses the passport module's _strategy method to create a new object from the one registered with the passport module's use method and stores it in the variable. Incidentally, I will not explain this in detail here, but in this case, the object mentioned above is JwtStrategy. JwtStrategy has an authenticate property, so subsequent processing can be executed without issues.
Now that we know the content of the strategy variable, let's look at the content of the authenticate property that the strategy object executes.
JwtStrategy.prototype.authenticate = function (req, options) {
var self = this;
var token = self._jwtFromRequest(req);
if (!token) {
return self.fail(new Error("No auth token"));
}
this._secretOrKeyProvider(
req,
token,
function (secretOrKeyError, secretOrKey) {
if (secretOrKeyError) {
self.fail(secretOrKeyError);
} else {
// Verify the JWT
JwtStrategy.JwtVerifier(
token,
secretOrKey,
self._verifOpts,
function (jwt_err, payload) {
if (jwt_err) {
return self.fail(jwt_err);
} else {
// Pass the parsed token to the user
var verified = function (err, user, info) {
if (err) {
return self.error(err);
} else if (!user) {
return self.fail(info);
} else {
return self.success(user, info);
}
};
try {
if (self._passReqToCallback) {
self._verify(req, payload, verified);
} else {
self._verify(payload, verified);
}
} catch (ex) {
self.error(ex);
}
}
}
);
}
}
);
};
First, it executes self._jwtFromRequest(req), runs the token extraction process we saw when creating the JwtStrategy class in NestJS, and obtains the token. If there is no token here, it throws an exception. After that, it executes this._secretOrKeyProvider, which has the key information set as an argument, and defines a callback function. By the way, JwtStrategy.JwtVerifier, which was not in the JwtStrategy of the passport-jwt module, is set around line 83 of strategy.js as follows:
JwtStrategy.JwtVerifier = require("./verify_jwt");
Looking at the processing in verify_jwt.js, we can see that it validates the token using the verify method of jsonwebtoken.
var jwt = require("jsonwebtoken");
module.exports = function (token, secretOrKey, options, callback) {
return jwt.verify(token, secretOrKey, options, callback);
};
From the above, we understand that the authenticate property first obtains JWS-formatted data, then performs signature verification if the data exists, and executes subsequent processing. In this case, the subsequent processing is the validate method we checked when creating the JwtStrategy class in NestJS.
By looking this far, I believe you have an image of what kind of function the createPassportContext function returns. Namely, the role of the createPassportContext function is to return a function that obtains a token, validates the token's signature, and executes the defined validate method. Therefore, the processing of the JwtStrategy we created runs only when this AuthGuard is called.
To summarize, the AuthGuard is executed in the following flow:
- Execution of the passport module's authenticate function
- Execution of the function of the authenticate property set in
passport-jwt'sJwtStrategy - Execution of the
jwtFromRequestmethod set in the constructor of jwt.strategy.ts - Execution of the secretOrKeyProvider method set in jwt.strategy.ts to validate the token
- Execution of the
validatemethod set injwt.strategy.ts - Unless options are specifically set, it uses the property name 'user' defined in passport's option.ts and passes the value of validate to the 'user' property in the request
- Since the guard passed, it returns
trueand finishes the guard processing.
Additionally, methods existing in AuthGuard can also be customized. As described in the documentation, such as by writing the following, you can freely customize it by setting arguments and return values for the methods defined within the createAuthGuard function.
@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt") {
canActivate(context: ExecutionContext) {
// Add your custom authentication logic here
// for example, call super.logIn(request) to establish a session.
return super.canActivate(context);
}
handleRequest(err, user, info) {
// You can throw an exception based on either "info" or "err" arguments
if (err || !user) {
throw err || new UnauthorizedException();
}
return user;
}
}
What is the string when calling AuthGuard?
Although I explained the internal functionality of AuthGuard earlier, when actually calling AuthGuard, we were specifying a string like "jwt" as an argument, as shown below:
export class JwtAuthGuard extends AuthGuard("jwt") {}
You might wonder why you have to explicitly specify a string. Well, the answer has already appeared. It lies in the following code, which was used when retrieving the strategy in lib/middleware/authenticate.js:
var layer = name[i];
// If no more strategies exist in the chain, authentication has failed.
if (!layer) {
return allFailed();
}
// Get the strategy, which will be used as prototype from which to create
// a new instance. Action functions will then be bound to the strategy
// within the context of the HTTP request/response pair.
var strategy, prototype;
if (typeof layer.authenticate == "function") {
strategy = layer;
} else {
prototype = passport._strategy(layer);
if (!prototype) {
return next(new Error('Unknown authentication strategy "' + layer + '"'));
}
strategy = Object.create(prototype);
}
First, pay attention to the name variable. The name variable is ultimately an array of the strings set when calling AuthGuard. I won't explain the details of why here, but if you're curious, you can trace the code from the createAuthGuard function to the code near where the createPassportContext function is executed, look at the authenticate method in lib/authenticator.js, and then check around line 89 of the authenticate function in lib/middleware/authenticate.js which performs the internal processing. By tracing it that way, you should be able to see what is being stored.
That covers the explanation of the name variable. Next, pay attention to the _strategy method part. Looking inside, it is implemented as follows:
Authenticator.prototype._strategy = function (name) {
return this._strategies[name];
};
The _strategies property also sounds familiar. The _strategies property was used by the passport module's use method to store the strategy name as the key and the strategy to be used as the value. Therefore, it is clear that the _strategy method is a process for retrieving the strategy to be used.
From the above, the identity of the string set as the argument for AuthGuard is clear: it is the key used to identify the strategy for the guard. While the identity is known, one might ask, "When was the string 'jwt' registered?" You can tell by looking at line 31 of the Strategy:
this.name = "jwt";
As shown, the string "jwt" is stored in the name property. And remember, the passport module's use method sets the value of the strategy's name property as the key if no name is specified. Therefore, if no name is set, the strategy we've been looking at is saved using "jwt" as the key. That is why it works when you specify "jwt" as the argument for AuthGuard.
Although I said it is saved with the string "jwt" if no name is set, in turn, you can also define it with a unique name. In fact, you can define a name in the second argument of PassportStrategy as follows:
export function PassportStrategy<T extends Type<any> = any>(
Strategy: T,
name?: string | undefined,
callbackArity?: true | number
): {
new (...args): InstanceType<T>;
};
And the passport.use part is designed to set the name if the name argument exists.
Based on the above, if you were to create the JwtStrategy like this:
export class JwtStrategy extends PassportStrategy(
Strategy,
"custom_strategy"
) {}
Then you can use the created strategy when calling AuthGuard by doing the following:
export class JwtAuthGuard extends AuthGuard("custom_strategy") {}
That's quite interesting, isn't it? With this feature, you could potentially change which guard is called for each environment. As a side note, AuthGuard can also accept strategy names as an array, as shown below:
export class JwtAuthGuard extends AuthGuard(['strategy_jwt_1', 'strategy_jwt_2', '...']) { ... }
If you do this, the endpoint will execute as soon as one of the strategy processes completes. This allows for customization, such as being able to validate requests coming in multiple forms.
Customizing JwtStrategy
Up to this point, we have looked at the functionality of JwtStrategy. By confirming its features, it feels like JwtStrategy can also be extended in various ways to fit requirements. Therefore, in this chapter, we will extend JwtStrategy to customize it so that it can handle tokens created and stored in various ways.
Requirements
This time, we assume the following for each token:
- The token stored in the cookie is a self-created token.
- The token in the Authorization header is a token obtained from Auth0.
Therefore, when a cookie token is retrieved, we will validate it with our own key, and when an Authorization header token is retrieved, we will obtain the key from Auth0 and validate it.
Completed Code
First, I will expand the entire code for jwt.strategy.ts.
import { ExtractJwt, SecretOrKeyProvider, Strategy } from "passport-jwt";
import { PassportStrategy } from "@nestjs/passport";
import { Injectable } from "@nestjs/common";
import { Request } from "express";
import { passportJwtSecret } from "jwks-rsa";
const secretOrKeyProvider: SecretOrKeyProvider = (
request,
rawJwtToken,
done
) => {
if (request.cookies?.token) {
return done(null, "Self-created verification key");
}
return passportJwtSecret({ jwksUri: "url" })(request, rawJwtToken, done);
};
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, "jwt") {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromExtractors([
(req) =>
req.cookies.token ?? ExtractJwt.fromAuthHeaderAsBearerToken()(req),
]),
ignoreExpiration: false,
secretOrKeyProvider: secretOrKeyProvider,
});
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}
There are two main points. First, we use ExtractJwt.fromExtractors in the JWT retrieval process to define our own function for obtaining the JWT token. Internally, it does the following:
- If a token exists in the cookie, it returns the value retrieved from there.
- If it does not exist, it returns the token in the Authorization header.
The second point is that the value set for secretOrKeyProvider is custom-created. If a token exists in the cookie, verification is performed using a key within our own project; otherwise, the key is obtained and verified from JWKS (JSON Web Key Set). The process of obtaining the key from JWKS is handled by the passportJwtSecret function. If you set the JWKS URI in the passportJwtSecret function, it will fetch the key. It then returns a function that conforms to the SecretOrKeyProvider callback function format while using that key. And we then execute the function received.
Note that when obtaining JWKS from Auth0, as described in the documentation, you can obtain it by specifying https://{Auth0 tenant domain}/.well-known/jwks.json as the URI.
Verification
First, create the guard as follows:
import { Injectable } from "@nestjs/common";
import { AuthGuard } from "@nestjs/passport";
@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt") {}
Prepare a method to create a JWT and set it in a cookie. Please keep in mind that I have prepared this based on the NestJS documentation to be able to use cookies in NestJS.
@Get('create/jswt')
async setJwt(@Res({ passthrough: true }) res: Response) {
const payload = { sub: 'userId', username: 'username' };
const token = await this.jwtService.signAsync(payload)
res.cookie('token', token)
}
This is the configuration of the module for calling the JwtService class. This time, I am creating it using the public key method referring to the links below, and setting that information.
https://weblabo.oscasierra.net/openssl-genrsa-secret-1/
https://weblabo.oscasierra.net/openssl-genrsa-public-1/
With this, calling the signAsync method will automatically sign using the set key.
imports: [JwtModule.register({
secret: "Key information (specify private key for RS256)",
signOptions: { algorithm: 'Explicitly set if not encrypted via HS256' },
}),],
Note that I have set the public key information in the JwtStrategy shown earlier. This is the method for operation confirmation. If token validation is OK, the string "test" will be returned.
@Get('jwt-strategy-test')
@UseGuards(JwtAuthGuard)
async testFn() {
return 'test'
}
Once this is done, you can use the curl command to verify that the string "test" is returned only when a token is set in the cookie and when an Auth0-issued Bearer token exists in the Authorization header.
Customizing the PassportStrategy Function
Finally, I will also customize the PassportStrategy function that wraps the strategy. The PassportStrategy function is very convenient, but it has the following drawbacks:
- Type completion does not work when setting options in the constructor.
- It is difficult to understand whether to set
secretOrKeyorsecretOrKeyProviderwithout grasping the internal processing. - Since both
secretOrKeyandsecretOrKeyProviderare optional, no static error occurs even if both are set by mistake. - No static error occurs even if the
validatemethod is not implemented.
Therefore, I will wrap the PassportStrategy function further and limit its functionality to make it easier to use without needing to know the internal structure.
Completed Code
The completed code is as follows:
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy, StrategyOptions } from "passport-jwt";
interface AbstractStrategyClass {
validate(...payload: any): any;
}
type KeyOptions = Omit<
StrategyOptions,
"secretOrKeyProvider" | "jwtFromRequest"
> &
Required<Pick<StrategyOptions, "secretOrKey">>;
type KeyProviderOptions = Omit<
StrategyOptions,
"secretOrKey" | "jwtFromRequest"
> &
Required<Pick<StrategyOptions, "secretOrKeyProvider">>;
type JwtFromRequest = Pick<StrategyOptions, "jwtFromRequest">;
const COOKIE_STRATEGY_NAME_WITH_KEY = "COOKIE_STRATEGY_NAME_WITH_KEY";
export const CookieStrategyWithKey = {
strategyName: COOKIE_STRATEGY_NAME_WITH_KEY,
strategy: (options: KeyOptions, cookieName: string) => {
const getTokenObject: JwtFromRequest = {
jwtFromRequest: (req) => req?.cookies[cookieName] ?? null,
};
abstract class CookieStrategyClassWithKey
extends PassportStrategy(Strategy, COOKIE_STRATEGY_NAME_WITH_KEY)
implements AbstractStrategyClass
{
constructor() {
super({ ...options, ...getTokenObject });
}
abstract validate(...payload: any): any;
}
return CookieStrategyClassWithKey;
},
};
CookieStrategyWithKey.strategy({ secretOrKey: "" }, "token");
const COOKIE_STRATEGY_NAME_WITH_KEY_PROVIDER =
"COOKIE_STRATEGY_NAME_WITH_KEY_PROVIDER";
export const CookieStrategyWithKeyProvider = {
strategyName: COOKIE_STRATEGY_NAME_WITH_KEY_PROVIDER,
strategy: (options: KeyProviderOptions, cookieName: string) => {
const getTokenObject: JwtFromRequest = {
jwtFromRequest: (req) => req?.cookies[cookieName] ?? null,
};
abstract class CookieStrategyClassWithKey
extends PassportStrategy(Strategy, COOKIE_STRATEGY_NAME_WITH_KEY_PROVIDER)
implements AbstractStrategyClass
{
constructor() {
super({ ...options, ...getTokenObject });
}
abstract validate(...payload: any): any;
}
return CookieStrategyClassWithKey;
},
};
const AUTHORIZATION_HEADER_STRATEGY_NAME_WITH_KEY =
"AUTHORIZATION_HEADER_STRATEGY_NAME_WITH_KEY";
export const AuthorizationHeaderStrategyWithKey = {
strategyName: AUTHORIZATION_HEADER_STRATEGY_NAME_WITH_KEY,
strategy: (options: KeyOptions) => {
const getTokenObject: JwtFromRequest = {
jwtFromRequest: (req) => ExtractJwt.fromAuthHeaderAsBearerToken()(req),
};
abstract class CookieStrategyClassWithKey
extends PassportStrategy(
Strategy,
AUTHORIZATION_HEADER_STRATEGY_NAME_WITH_KEY
)
implements AbstractStrategyClass
{
constructor() {
super({ ...options, ...getTokenObject });
}
abstract validate(...payload: any): any;
}
return CookieStrategyClassWithKey;
},
};
const AUTHORIZATION_HEADER_STRATEGY_NAME_WITH_KEY_PROVIDER =
"AUTHORIZATION_HEADER_STRATEGY_NAME_WITH_KEY_PROVIDER";
export const AuthorizationHeaderStrategyWithKeyProvider = {
strategyName: AUTHORIZATION_HEADER_STRATEGY_NAME_WITH_KEY_PROVIDER,
strategy: (options: KeyProviderOptions) => {
const getTokenObject: JwtFromRequest = {
jwtFromRequest: (req) => ExtractJwt.fromAuthHeaderAsBearerToken()(req),
};
abstract class CookieStrategyClassWithKey
extends PassportStrategy(
Strategy,
AUTHORIZATION_HEADER_STRATEGY_NAME_WITH_KEY_PROVIDER
)
implements AbstractStrategyClass
{
constructor() {
super({ ...options, ...getTokenObject });
}
abstract validate(...payload: any): any;
}
return CookieStrategyClassWithKey;
},
};
The code provided is designed to enable JWT verification in the following cases:
- A JWT format token exists in the cookie, and the verification key is available.
- A JWT format token exists in the cookie, and a separate process to obtain the key is required.
- A Bearer token exists in the Authorization header, and the verification key is available.
- A Bearer token exists in the Authorization header, and a separate process to obtain the key is required.
Having confirmed what can be done with this file, let's look at the key points in the code. First, by setting the interface below, we ensured that an error occurs if the validate method is missing when creating a strategy.
interface AbstractStrategyClass {
validate(...payload: any): any;
}
The reason for using spread arguments is to support cases where the Request object is set in the first argument when the passReqToCallback property is true.
Next, by defining the types below, we ensured that the options to be set differ depending on whether you have your own key or need to obtain key information separately. Also, since we want to limit the way tokens are obtained, we defined types to allow creating separate objects for obtaining tokens.
type KeyOptions = Omit<
StrategyOptions,
"secretOrKeyProvider" | "jwtFromRequest"
> &
Required<Pick<StrategyOptions, "secretOrKey">>;
type KeyProviderOptions = Omit<
StrategyOptions,
"secretOrKey" | "jwtFromRequest"
> &
Required<Pick<StrategyOptions, "secretOrKeyProvider">>;
type JwtFromRequest = Pick<StrategyOptions, "jwtFromRequest">;
By using these types, you can minimize the options when calling. With the preparation complete, let's check the code that extends the PassportStrategy function.
const COOKIE_STRATEGY_NAME_WITH_KEY = 'COOKIE_STRATEGY_NAME_WITH_KEY'
export const CookieStrategyWithKey = {
strategyName: COOKIE_STRATEGY_NAME_WITH_KEY,
strategy: (options: KeyOptions, cookieName: string) => {
const getTokenObject: JwtFromRequest = {
jwtFromRequest: (req) => req?.cookies[cookieName] ?? null
}
abstract class CookieStrategyClassWithKey extends PassportStrategy(Strategy, COOKIE_STRATEGY_NAME_WITH_KEY) implements AbstractStrategyClass {
constructor() {
super({ ...options, ...getTokenObject })
}
abstract validate(...payload: any): any
}
return CookieStrategyClassWithKey;
}
}
This object is a collection of information for verifying tokens signed with our own key. Each property of the defined object is assumed to be as follows: strategyName is the name to call the strategy defined, and strategy is the function to get an abstract class based on JwtStrategy.
Let's take a closer look at the content of the strategy property.
strategy: (options: KeyOptions, cookieName: string) => {
const getTokenObject: JwtFromRequest = {
jwtFromRequest: (req) => req?.cookies[cookieName] ?? null
}
abstract class CookieStrategyClassWithKey extends PassportStrategy(Strategy, COOKIE_STRATEGY_NAME_WITH_KEY) implements AbstractStrategyClass {
constructor() {
super({ ...options, ...getTokenObject })
}
abstract validate(...payload: any): any
}
return CookieStrategyClassWithKey;
}
First, we set the previously created KeyOptions type for the arguments. This allows the strategy to run with the secretOrKey property when using this object. After the arguments, we defined an object to obtain JWT using the JwtFromRequest type defined earlier. The type of the jwtFromRequest property in the JwtFromRequest type is a function that takes a Request object as an argument and returns a string or null, as follows:
export interface JwtFromRequestFunction {
(req: express.Request): string | null;
}
And since the CookieStrategyWithKey object we are looking at now obtains tokens from Cookies, we have it take the specified token from the Request object's Cookies and return null if it doesn't exist. Note that you cannot specify the Cookie name to retrieve here, so we have set the Cookie name to be retrieved as an argument for the function defined in the strategy property. When obtaining from the Authorization Header, the format of the token is fixed, so it is not set as an argument.
Finally, we created an abstract class using the AbstractStrategyClass interface. Basically, it's an abstraction of the JwtStrategy class creation using the PassportStrategy function we've seen so far. However, since the value set in the constructor must have properties of the StrategyOptions type, we are passing a combination of the previously created token acquisition object and the argument object via spread syntax.
This is the explanation of the object actually used. While there are fine differences such as the presence or absence of arguments and the types used in objects that use secretOrKeyProvider or objects that obtain tokens from the Authorization Header, it is not worth explaining separately, so this concludes the content of the code.
When actually using it, you can call it as follows and use it as before.
import { Injectable } from '@nestjs/common';
import { jwtConstants } from './constants';
import { AuthorizationHeaderStrategyWithKey } from 'customized-jwt-strategy';
@Injectable()
export class JwtStrategy extends AuthorizationHeaderStrategyWithKey.strategy({ secretOrKey: jwtConstants.secret }) {
constructor() {
super();
}
async validate(payload: any) {
return { userId: payload.sub, username: payload.username };
}
}
In this way, the required option becomes only secretOrKey, and since an interface is set, a static error is generated if the validate function is not defined. I am satisfied with this as I think it has become easier to use.
Conclusion
This time, we started from how to use passport in NestJS according to the documentation, and went on to customize JwtStrategy. Most of what was explained was very detailed, just for the purpose of creating a guard, but there was a deep world there. By examining the internal structure in detail, I was able to better appreciate the understanding of strategies and their convenience, which was great.
However, I am exhausted. Although the area covered was quite narrow, I am more tired than when I wrote the article about Docker. Since I worked hard on it, I hope it reaches people who are having trouble with strategies in NestJS. Thank you for reading this far.
Discussion