Skip to content

Instantly share code, notes, and snippets.

@LunaticMuch
Created February 4, 2023 12:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LunaticMuch/63696e2a001a292bd2c839c92941c10c to your computer and use it in GitHub Desktop.
Save LunaticMuch/63696e2a001a292bd2c839c92941c10c to your computer and use it in GitHub Desktop.
Token generation with jose
import {SignJWT, jwtVerify, type JWTPayload} from 'jose';
export async function sign(payload: Token, secret: string): Promise<string> {
const iat = Math.floor(Date.now() / 1000);
const exp = iat + 60* 60; // one hour
return new SignJWT({...payload})
.setProtectedHeader({alg: 'HS256', typ: 'JWT'})
.setExpirationTime(exp)
.setIssuedAt(iat)
.setNotBefore(iat)
.sign(new TextEncoder().encode(secret));
}
export async function verify(token: string, secret: string): Promise<Token> {
const {payload} = await jwtVerify(token, new TextEncoder().encode(secret));
// run some checks on the returned payload, perhaps you expect some specific values
// if its all good, return it, or perhaps just return a boolean
return payload;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment