Generates a public and private key
Converts a key object into a string
converts a private key back from a string
same but for public keys
signs a payload and returns a jwt
validates a jwt and returns the payload and a validation value
import { generateKeyPair, keyToString, stringToPrivateKey, stringToPublicKey, sign, verify } from './jwtFuncs.js'
// generate token function returns a signed json web token that includes, user id, and expiration date, and creation date,
async function generateToken(userId, privateKey) {
// constant for expiration time 6hours
const expirationTime = 6 * 60 * 60 * 1000
// get current time
const currentDate = new Date()
// get expiration date
const expirationDate = new Date(currentDate.getTime() + expirationTime)
// get creation date
const creationDate = new Date()
// create payload
const payload = {
userId: userId,
expirationDate: expirationDate,
creationDate: creationDate
}
const jsonPayload = JSON.stringify(payload)
console.log(jsonPayload);
// sign payload
const token = await sign(jsonPayload, privateKey)
// return token
return token
}
export default {
async fetch(request, env) {
const url = new URL(request.url)
const pathname = url.pathname
var privateKey = env.PRK
var publicKey = env.PUK
privateKey = await stringToPrivateKey(privateKey)
publicKey = await stringToPublicKey(publicKey)
if (pathname === '/sign') {
const token = await generateToken(911, privateKey)
return new Response(token)
}
else if (pathname === '/verify') {
const token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.IntcInVzZXJJZFwiOjkxMSxcImV4cGlyYXRpb25EYXRlXCI6XCIyMDIzLTA4LTEzVDAzOjA4OjI3LjgyOFpcIixcImNyZWF0aW9uRGF0ZVwiOlwiMjAyMy0wOC0xMlQyMTowODoyNy44MjhaXCJ9Ig.6Es_PUscpIPV2Q1LI3Dya0E-qCcsA0Vemp6sL/haLc+dy0GfqCjM90tyMZctK3P8yPJrzNUaYRsUkox+vn61I51uacaYg5Am2W3WTspUwpBz8jiilUMPXP1Z5sbGlD0JOc3RCC9uHKJe8940vWWJBZNq4dwVJDJ6386V0jKyXkqPMJs6aZkyOsGQcm4F7tBYnUUusSqnC4jB1iAVmJ/HxY4i5cLDda1Ftp3odxS0PcCEYbeGyJndpbtWkNcFp+3hZIuSc1O6F3xqFJwyew2umvYML1mvFCYbbYtKZkXf2fs7Lrb/tEp+apPxco5kSV7GyeL3XqqcB0SyF/y8EQWFzQ'
const { isValid, payload } = await verify(token, publicKey);
if (isValid) {
console.log("Valid token");
console.log(payload);
}
return new Response(isValid)
} else {
return new Response('Not Found', { status: 404 })
}
}
}
Disclaimer: A large part of this was written with the help of Github Copilot, it seems sound, and the crypto is provided by the webCrypto API so that is unlikely to have issues, but still please point out any security issues so I can fix them for anyone else who finds this on google.