Skip to content

Instantly share code, notes, and snippets.

@aungthuoo
Last active March 2, 2024 14:49
Show Gist options
  • Save aungthuoo/3c433d85b7d983b62c5a1c99339eb806 to your computer and use it in GitHub Desktop.
Save aungthuoo/3c433d85b7d983b62c5a1c99339eb806 to your computer and use it in GitHub Desktop.

Node.js JWT simple example

Installation

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);
  }
});

request

POST /api/login
Content-type: appliction/json
{ username: "Bob", password: "password" } 


// response 
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6IkJvYiIsInBhc3
N3b3JkIjoicGFzc3dvcmQiLCJyb2xlIjoidXNlciIsImlhdCI6MTYwMDc2MzI1NiwiZ
XhwIjoxNjAwNzY2ODU2fQ.-OBn8nIEmJqdNc9XfoUVVcZc7PEVUWHVQOP85YIlygo

Example 3: With middleware

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){
    //…
});

Example 4: With multiple middleware

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) {
    //…
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment