Skip to content

Commit

Permalink
Add version number to token payload
Browse files Browse the repository at this point in the history
  • Loading branch information
emlun committed Aug 6, 2024
1 parent 8999194 commit 212feee
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/middlewares/auth.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,13 @@ import { jwtVerify, SignJWT } from 'jose';
import config from "../../config";
import { getUserByDID, UserEntity } from "../entities/user.entity";


type TokenPayloadVersion = 0;
const TOKEN_PAYLOAD_VERSION: TokenPayloadVersion = 0;

type AppTokenPayload = {
// Increment TokenPayloadVersion whenever AppTokenPayload content changes to invalidate existing tokens
v: TokenPayloadVersion;
did: string;
}

Expand All @@ -15,7 +21,10 @@ export type AppTokenUser = {

export async function createAppToken(user: UserEntity): Promise<string> {
const secret = new TextEncoder().encode(config.appSecret);
const payload: AppTokenPayload = { did: user.did };
const payload: AppTokenPayload = {
v: TOKEN_PAYLOAD_VERSION,
did: user.did,
};
return await new SignJWT(payload)
.setProtectedHeader({ alg: "HS256" })
.sign(secret);
Expand All @@ -25,7 +34,14 @@ async function verifyApptoken(jwt: string): Promise<AppTokenPayload | null> {
const secret = new TextEncoder().encode(config.appSecret);
try {
const { payload, protectedHeader } = await jwtVerify(jwt, secret);
return payload as AppTokenPayload;
if (payload?.v === TOKEN_PAYLOAD_VERSION) {
// The combination of a valid signature and the correct version
// guarantees that the payload has the correct structure.
return payload as AppTokenPayload;
} else {
console.log(`Incorrect token version: expected: ${TOKEN_PAYLOAD_VERSION}, got: ${payload?.v}`);
return null;
}
}
catch (err) {
console.log('Signature verification failed');
Expand Down

0 comments on commit 212feee

Please sign in to comment.