Utilizing Typescript alongside Express and JWT for Bearer Authorization presents a specific challenge. In this situation, I am developing the authorize middleware with JWT as specified and attempting to extricate the current user from the JWT token.
Sample code snippet:
import * as jwt from 'jsonwebtoken';
import * as dotenv from 'dotenv';
import {NextFunction, Response, Request} from "express";
import {
VerifyOptions,
Algorithm,
JsonWebTokenError,
TokenExpiredError,
NotBeforeError,
Secret,
JwtPayload
} from "jsonwebtoken";
....
try {
// Verify the token
let result = jwt.verify(authToken, accessTokenSecret, accessTokenOptions)
console.log("Type of: String"+(result instanceof String) )
console.log("Type of: JwtPayload " + (result instanceof JwtPayload) ); // Error
next();
} catch (error){
...
}
}
The challenge is in confirming if 'result' is an instance of JwtPayload. Since JwtPayload is an interface, I consistently encounter the error 'Argument of type 'string | JwtPayload' is not assignable to parameter of type 'string'.'
For the sake of this discussion, let's assume that the token is always verified successfully.
Let's delve into the data stored within 'result'!
{
user: {id: 1, username: 'ariel'},
iat: 1234,
exp: 1278
}
All I aim to do is extract the user information from the 'result'. However, the aforementioned error keeps interfering with this process.