Skip to content

Commit

Permalink
Add util to verify JWT
Browse files Browse the repository at this point in the history
  • Loading branch information
D-Pow committed Aug 8, 2024
1 parent ea29ad2 commit a6bfca2
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/utils/Jwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,3 +111,42 @@ export async function encodeJwt(text: string, {

return jwt;
}


/**
* Verifies a JWT token.
* Note: This shouldn't be done client-side as it exposes the secret.
*/
export async function verifyJwt(jwt: string, signature: Parameters<Crypto['subtle']['verify']>[2], {
alg = 'HS256',
typ = 'JWT',
secret = '',
} = {}) {
const [ encodedHeader, encodedPayload, signatureStr ] = jwt.split('.');

let algorithm = alg
.replace(/^hs/i, 'sha')
.replace(/^\D+/gi, match => match.toLowerCase());
algorithm = algorithm.replace(/^sha/i, 'SHA-');
const algoInfo = {
name: 'HMAC',
hash: algorithm,
};

const signingKey = await self.crypto.subtle.importKey(
'raw',
new TextEncoder().encode(secret),
algoInfo,
false,
[ 'verify' ],
);

return await self.crypto.subtle.verify(
'HMAC',
signingKey,
signature,
new TextEncoder().encode(
`${encodedHeader}.${encodedPayload}`,
),
);
}

0 comments on commit a6bfca2

Please sign in to comment.