How Do I Make This JWT Authentication Work w/ a Database Full of Users?

Bruce Gust
Bruce Gust used Ask the Experts™
on
This works:

const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
const mongoose = require("mongoose");
const session = require("express-session");
const MongoDBStore = require("connect-mongodb-session")(session);
const csrf = require("csurf");

const MONGODB_URI =
  "mongodb+srv://username:password@brucegust-wxyz.mongodb.net/applied";

app.get("/api", (req, res) => {
  //console.log("hello");
  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@domain.com"
  };

  jwt.sign({ user: user }, "secretkey", { expiresIn: "30s" }, (err, token) => {
    res.json({
      token: token
    });
    console.log("yes");
  });
});

// format of Token
// Authorization: Bearer <access_token>

//verify Token

function verifyToken(req, res, next) {
  //get auth header value
  const bearerHeader = req.headers["authorization"];
  // check if bearer is undefined
  if (typeof bearerHeader !== "undefined") {
    // split at the space
    const bearer = bearerHeader.split(" ");
    //get token from array
    const bearerToken = bearer[1];
    console.log(bearerToken);
    //set the token
    req.token = bearerToken;
    next();
  } else {
    //forbidden
    res.sendStatus(403);
  }
}

mongoose
  .connect(MONGODB_URI)
  .then(result => {
    app.listen(5000);
  })
  .catch(err => {
    console.log(err);
  });

Open in new window


What I need to do is take the above tutorial and edit it so I can take the incoming JWT and match it to, not one user, but one user amongst a database with over 700 users.

How would I do that?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
The way I understand it is the JWT library will validate the token. You can include additional information in the token which you can extract that you can then use to identify your user - for instance an unguessable  hash or similar that is linked to the user record.
Bruce GustPHP Developer

Author

Commented:
Julian, I figured it out. Actually, the answer was right in front of me with "authData" on line 26.

How do I parse that out so I can see the username etc?
Most Valuable Expert 2017
Distinguished Expert 2018
Commented:
That depends on what you put in there. If you look at line 34 you are adding your user data to an object with property user.

If you console.log out authData you should see that reflected there so you should be able to get it using something like
authData.user.id - it's been a while since I worked with JWT so I am a bit rusty but I seem to remember you can do it like that.
Bruce GustPHP Developer

Author

Commented:
Got it!
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
You are welcome.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial