1
\$\begingroup\$

Here is my code to implement authentication in a Node/Express/Sequelize project. This is my first time using JWT and I would appreciate any help!

// Load required packages
const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');
const config = require('../config');
const User = require('../models').User;

exports.authenticate = function(req, res) {
  const username = req.body.username;
  const password = req.body.password;
  User.findOne({
    where: { username: username }
  }).then((user) => {
    // Make sure the password is correct
    if (user.verifyPassword(password)) {
      const token = jwt.sign({
        username: user.username
      }, config.jwtSecret);
      res.json({
        success: true,
        token: token,
        username: user.username
      });
    }
  }).catch((error) => {
    console.error(error);
    res.sendStatus(404);
  });
}

exports.isAuthenticated = expressJwt({ secret: config.jwtSecret });
\$\endgroup\$
1
\$\begingroup\$

Though not in Javascript, my uses of JWT have always used the password as the JWT secret. The JWT payload is whatever you need to identify the user -- username in your case. You can add in a CSRF token of some sort as well. I have an example on my GitHub that is a very simple application using JWT as the authentication mechanism - https://github.com/dave-shawley/readings/blob/7d2504587daa6a174fc3cbc0a5478fa817412eea/readings/static/js/login.js#L10-L26 is the javascript login code. Mind you that I am most certainly not a javascript programmer so don't read too much into my example for style advice ;)

My login code builds a JWT payload that looks something like:

{
  "exp": 1488027170,
  "iss": "https://whatever.example.com/login",
  "csrf": "123456ABCDEF",
  "nbf": 1488026870
}

where "nbf" is the current time, "exp" is the expiration time, and "iss" is the referring web site. "csrf" is a one-time token that is embedded in the HTML form.

I encode this structure using the entered password as the secret and pass the resulting token to my login endpoint. I have the user name in a secured cookie but it could be passed in the JWT payload as well. On the receiving side, I look up the user information in my data store by the user name from the cookie. Then I verify that the JWT payload was signed using the password as the secret and that it is still valid. If everything checks out, then the user is authenticated.

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

I can't be of much help with JWT, however if you are able to use es7 features, I would recommend utilising them.

const jwt = require('jsonwebtoken');
const expressJwt = require('express-jwt');
const config = require('../config');
const { User } = require('../models');

exports.authenticate = async (req, res) => {
  const { username, password } = req.body; 

  try {
    const user = await User.findOne({ username });
    if(!user.verifyPassword(password)) {
      //.. should send some sort of response here
      return;
    }
    const token = jwt.sign({
      username: user.username
    }, config.jwtSecret);

    res.json({
      success: true,
      token: token,
      username: user.username
    });
  } catch (error) {
    console.error(error);
    res.sendStatus(404);
  }
}

exports.isAuthenticated = expressJwt({ secret: config.jwtSecret });
| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.