npm install jsonwebtoken
// index.js
const jwt = require("jsonwebtoken");
const secret = "horse battery staple";
const users = [
{ username: "Alice", password: "password", role: "admin" },
{ username: "Bob", password: "password", role: "user" },
];
app.post("/api/login", function (req, res) {
const { username, password } = req.body;
const user = users.find(function (u) {
return u.username === username && u.password === password;
});
if (user) {
const token = jwt.sign( user, secret, {expiresIn: "1h"});
res.json({ token });
} else {
res.sendStatus(401);
}
});
POST /api/login
Content-type: appliction/json
{ username: "Bob", password: "password" }
// response
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkJvYiIsInBhc3
N3b3JkIjoicGFzc3dvcmQiLCJyb2xlIjoidXNlciIsImlhdCI6MTYwMDc2MzI1NiwiZ
XhwIjoxNjAwNzY2ODU2fQ.-OBn8nIEmJqdNc9XfoUVVcZc7PEVUWHVQOP85YIlygo
function auth(req, res, next) {
const authHeader = req.headers["authorization"];
if(!authHeader) return res.sendStatus(401);
//Authorization: Bearer [token]
const [ type, token ] = authHeader.split(" ");
if(type !== "Bearer") return res.sendStatus(401);
jwt.verify(token, secret, function(err, data) {
if(err) res.sendStatus(401);
else next();
});
}
app.get("/api/records", auth, function(req, res){
//…
});
function onlyAdmin(req, res, next) {
const [ type, token ] = req.headers["authorization"].split(" ");
jwt.verify(token, secret, function(err, user) {
if(user.role === "admin") next();
else res.sendStatus(403);
});
}
function auth(req, res, next) {
const authHeader = req.headers["authorization"];
if(!authHeader) return res.sendStatus(401);
//Authorization: Bearer [token]
const [ type, token ] = authHeader.split(" ");
if(type !== "Bearer") return res.sendStatus(401);
jwt.verify(token, secret, function(err, data) {
if(err) res.sendStatus(401);
else next();
});
}
app.delete("/api/records/:id", auth, onlyAdmin, function(req, res) {
//…
});