Skip to content

Instantly share code, notes, and snippets.

@Tribhuwan-Joshi
Created July 14, 2023 08:15
Show Gist options
  • Save Tribhuwan-Joshi/c15577a792d2fbf16dd076d2b26096f1 to your computer and use it in GitHub Desktop.
Save Tribhuwan-Joshi/c15577a792d2fbf16dd076d2b26096f1 to your computer and use it in GitHub Desktop.
JWT overview
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