javascriptexpressjwtpassport.jspassport-jwt

JWT token does not expire


For whatever reason, the token generated by jsonwebtoken never expires.

Here is my code so far.

auth.ts Middleware.

// Libs
import { Express, Request, Response, NextFunction } from "express";
import { PassportStatic } from "passport";
import { Strategy as JWTStrategy, ExtractJwt } from "passport-jwt";

// Users
import { usersDB } from "../users";

const setupAuth = (api: Express, passport: PassportStatic) => {

  const strategy = new JWTStrategy(
    {
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: "123456qwerty",
      algorithms: ["HS256"],
    },
    (payload, cb) => {
      try {
        const { sub } = payload;

        const user = usersDB.find((u) => u.username === sub);

        if (user) {
          return cb(null, user);
        } else {
          return cb(null, false);
        }
      } catch (e) {
        return cb(e);
      }
    }
  );

  api.use(passport.initialize());

  passport.use(strategy);
};

export default setupAuth;

Login route

import { Request, Response } from "express";

import { usersDB, validatePassword } from "../../users";

import { genJWT } from "../../utils/auth";

const login = (req: Request, res: Response) => {
  const { username, password } = req.body;

  const user = usersDB.find((u) => u.username === username);

  if (!user) {
    return res
      .status(401)
      .json({ status: "fail", message: "Invalid username or password" });
  }

  if (!validatePassword(password, user.salt, user.hash)) {
    return res
      .status(401)
      .json({ status: "fail", message: "Invalid username or password" });
  }

  const token = genJWT(user.username);

  res.status(200).json({ status: "success", token });
};

export default login;

And the jwt token generator

import jwt from "jsonwebtoken";

export const genJWT = (username: string) => {
  const token = jwt.sign({ sub: username, iat: Date.now() }, "123456qwerty", {
    expiresIn: "1min",
    algorithm: "HS256",
  });

  return token;
};

Then the secured routes

// Lib
import { Express } from "express";
import { PassportStatic } from "passport";

// GET
import root from "./GET/root";
import currentUser from "./GET/current-user";
import privateContent from "./GET/private-content";

// POST
import register from "./POST/register";
import login from "./POST/login";
import logout from "./POST/logout";

const setupRoutes = (api: Express, passport: PassportStatic) => {
  api.get("/", root);
  api.get(
    "/current-user",
    passport.authenticate("jwt", { session: false }),
    currentUser
  );
  api.get(
    "/private-content",
    passport.authenticate("jwt", { session: false }),
    privateContent
  );

  api.post("/register", register);
  api.post("/login", login);
  api.post("/logout", logout);
};

export default setupRoutes;

So the API is working, able to generate jwt token, able to authenticate with the token. It is able to validate too if I modify the token. But the problem is I can forever use the token. It never expires.

Is there something I missed?

Thanks in advance.


Solution

  • Ok when I removed

    iat: Date.now()
    

    from the jwt.sign, now the token does expire. So never put iat, let jsonwebtoken generate it.