Created
July 14, 2023 08:15
-
-
Save Tribhuwan-Joshi/c15577a792d2fbf16dd076d2b26096f1 to your computer and use it in GitHub Desktop.
JWT overview
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
const express = require("express"); | |
const jwt = require("jsonwebtoken"); | |
const app = express(); | |
app.get("/api", (req, res) => { | |
res.json({ | |
message: "Welcome to the API", | |
}); | |
}); | |
app.post("/api/posts", verifyToken, (req, res) => { | |
jwt.verify(req.token, "secretKey", (err, authData) => { | |
if (err) res.sendStatus(403); | |
else { | |
res.json({ | |
message: "Post created", | |
authData, | |
}); | |
} | |
}); | |
}); | |
app.post("/api/login", (req, res) => { | |
// Mock user | |
const user = { id: 1, username: "brad", email: "[email protected]" }; | |
jwt.sign({ user }, "secretKey", (err, token) => { | |
res.json({ | |
token, | |
}); | |
}); | |
}); | |
// verify Token | |
// FORMAT -> Authorization : Bearer <access_token> | |
function verifyToken(req, res, next) { | |
// Get auth header value | |
const bearerHeader = req.headers["authorization"]; | |
console.log(req.headers); | |
// check if bearer is undefined | |
if (typeof bearerHeader !== "undefined") { | |
// spilt at space | |
const bearer = bearerHeader.split(" "); | |
// Get token from array | |
const bearerToken = bearer[1]; | |
req.token = bearerToken; | |
next(); | |
} else { | |
res.sendStatus(403); | |
} | |
} | |
app.listen(5000, () => console.log("server started")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment