new jwt functions

This commit is contained in:
Ulf Gebhardt 2023-05-05 17:19:15 +02:00
parent 4e78dcddc1
commit 36d40cbe40
Signed by: ulfgebhardt
GPG Key ID: DA6B843E748679C9
2 changed files with 20 additions and 9 deletions

View File

@ -1,5 +1,5 @@
import { JwtPayload } from 'jsonwebtoken' import { JWTPayload } from 'jose'
export interface CustomJwtPayload extends JwtPayload { export interface CustomJwtPayload extends JWTPayload {
gradidoID: string gradidoID: string
} }

View File

@ -1,22 +1,33 @@
import { verify, sign } from 'jsonwebtoken' import { SignJWT, jwtVerify } from 'jose'
import { CONFIG } from '@/config/' import { CONFIG } from '@/config/'
import { LogError } from '@/server/LogError' import { LogError } from '@/server/LogError'
import { CustomJwtPayload } from './CustomJwtPayload' import { CustomJwtPayload } from './CustomJwtPayload'
export const decode = (token: string): CustomJwtPayload | null => { export const decode = async (token: string): Promise<CustomJwtPayload | null> => {
if (!token) throw new LogError('401 Unauthorized') if (!token) throw new LogError('401 Unauthorized')
try { try {
return <CustomJwtPayload>verify(token, CONFIG.JWT_SECRET) const secret = new TextEncoder().encode(CONFIG.JWT_SECRET)
const { payload } = await jwtVerify(token, secret, {
issuer: 'urn:example:issuer', // TODO urn
audience: 'urn:example:audience', // TODO urn
})
return payload as CustomJwtPayload
} catch (err) { } catch (err) {
return null return null
} }
} }
export const encode = (gradidoID: string): string => { export const encode = async (gradidoID: string): Promise<string> => {
const token = sign({ gradidoID }, CONFIG.JWT_SECRET, { const secret = new TextEncoder().encode(CONFIG.JWT_SECRET)
expiresIn: CONFIG.JWT_EXPIRES_IN, const token = await new SignJWT({ gradidoID, 'urn:example:claim': true }) // TODO urn
}) .setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setIssuer('urn:example:issuer') // TODO urn
.setAudience('urn:example:audience') // TODO urn
.setExpirationTime(CONFIG.JWT_EXPIRES_IN)
.sign(secret)
return token return token
} }