Created
August 5, 2024 02:16
-
-
Save klys/ab14be3ac062a7a5c16e064923178091 to your computer and use it in GitHub Desktop.
ExpressJS+jose+cookieHttpOnly
This file contains 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 express from "express" | |
import * as jose from 'jose' | |
import cookieParser from "cookie-parser" | |
import fs from 'fs' | |
/* | |
const privateKey = fs.readFileSync('./ec-secp256k1-priv-key.pem', 'utf8'); | |
const publicKey = fs.readFileSync('./ec-secp256k1-pub-key.pem', 'utf8'); | |
const privateKeyObject = await jose.importPKCS8(privateKey, 'pem'); | |
const publicKeyObject = await jose.importSPKI(publicKey, 'pem'); | |
*/ | |
const { publicKey, privateKey } = await jose.generateKeyPair('RS256', { modulusLength: 4096 }); | |
const port = "4001"; | |
const app = express(); | |
app.use(cookieParser()); | |
//const key = await jose.generate('ECDSA', { crv: 'P-256' }); | |
//const publicKey = await key.export(); | |
//const privateKey = await key.export({ privatePart: true }); | |
const verifyJWT = async (req, res, next) => { | |
const token = req.cookies.jwt; | |
console.log(token) | |
if (!token) return res.status(401).json({ message: 'Unauthorized' }); | |
try { | |
const { payload } = await jose.jwtVerify(token, publicKey); | |
req.user = payload.user; | |
next(); | |
} catch (error) { | |
console.error(error); | |
res.status(401).json({ message: 'Invalid token' }); | |
} | |
} | |
app.head("/api/v1/authenticate", async (req, res) => { | |
const user = { id: 1, username: 'user1' }; | |
const jwt = await new jose.SignJWT({ user }) | |
.setProtectedHeader({ alg: 'RS256' }) | |
.setIssuedAt() | |
.setExpirationTime('1h') | |
.sign(privateKey); | |
res.cookie('jwt', jwt, { httpOnly: true }); | |
res.json({ message: 'Login successful' }); | |
}) | |
app.get("/api/v1/info", verifyJWT, (req, res) => { | |
res.json({info:"information"}) | |
}) | |
app.listen(port,() => console.log("API running on port "+port)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment