Created
October 4, 2023 15:22
-
-
Save mallendeo/a848eab32227d6d54087733a27013891 to your computer and use it in GitHub Desktop.
Sign JWT using Jose
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as jose from 'jose' | |
const JWT_SECRET = new TextEncoder().encode(ENV.JWT_SECRET) | |
export const signJWT = async ( | |
data: Record<any, any>, | |
opts?: { | |
iat?: number | |
exp?: string | number | |
}, | |
) => { | |
const alg = 'HS256' | |
const jwt = await new jose.SignJWT(data) | |
.setProtectedHeader({ alg }) | |
.setIssuedAt(opts?.iat) | |
.setIssuer('example.app') | |
.setAudience('example.app') | |
.setExpirationTime(opts?.exp || '1h') | |
.sign(JWT_SECRET) | |
return jwt | |
} | |
export const verifyJWT = async (jwt: string) => { | |
const { payload } = await jose.jwtVerify(jwt, JWT_SECRET, { | |
issuer: 'example.app', | |
audience: 'example.app', | |
}) | |
return payload | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment