The validity of the JWT token is perpetual

It seems that the token created by jsonwebtoken does not have an expiration.

Below is my current code:

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;

While the API is functioning well and can generate and authenticate with the JWT token, the issue lies in its infinite usability without expiry. Is there a step I may have overlooked?

Thank you for your help.

Answer №1

After removing the line mentioned below

iat: Date.now()

from the jwt.sign function, I noticed that the token now expires properly. It seems better to let jsonwebtoken handle the generation of the 'iat' property.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to add items to your cart based on a matching product ID?

My challenge is to add an item to a list only if it matches the id, ensuring that only one item is added to the cart. I've attempted various methods but React doesn't seem to recognize my item's id. Below is the code excerpt where I'm ...

Challenges with Data Transfer in VueJS and VUEX

Here is the code snippet for my component: <div id="event-picker"> <template v-for="event in $store.state.events"> <a href="#" v-on:click.prevent="$store.dispatch('prepareEventForm', event)& ...

Struggling to find the right look for identical items

I'm currently working on a project where I need to identify and hide duplicate values in a table. The goal is to only display unique values in the first column and hide any duplicates from view. However, I'm running into an issue when trying to h ...

Using Javascript with Express.js to consistently provide status updates to the client

I'm looking to establish a system where my express backend consistently updates the client on the progress of a process. To demonstrate this, I have set up a sample backend: import express from 'express'; const app = express(); app.delete( ...

What is the reason behind ValidatorValidate() validating all RequiredFieldValidator controls on the page?

Can you explain why the function ValidatorValidate(v) validates all the RequiredFieldValidator controls on the page instead of just executing for RequiredFieldValidator1? Here is the code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> ...

Before inserting a string into JSON in PHP, the length of the string should be included

When sending a POST variable containing a JavaScript dictionary to a PHP file via Ajax, the value of this POST variable is being parsed as a PHP dictionary. However, I noticed that the length of each String value is added before the actual string in the PH ...

Concern with transferring the data to the emailTemplate ejs document

Seeking assistance in passing the token to an email Template, specifically an ejs file named emailTemplate.ejs. Currently, the token is not rendering as data but rather as plain text, displaying the variable name instead of its value. See below for the cod ...

What is the process of displaying text within a link?

I have a basic webpage where I want the text to display from a link. Here is my website: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Encyclopedia</title> <link href="test.css" re ...

How to interrupt a JQuery animation and restart it from the middle?

Currently, I am tackling my first JQuery project and facing a challenge. As the user mouseleaves the .container, the animation does not reset but continues as if they are still within it. My goal is to have the animation revert in reverse if the user decid ...

The variable in my NodeJS code is persisting across multiple requests and not being reset as expected

After setting up a project with the help of Typescript-Node-Starter, I have successfully created a controller and a route to call a specific function. import { Request, Response } from "express"; import axios from "axios"; import { pars ...

What is causing the Angular-UI TypeAhead code to display all items instead of filtered items?

I have been experimenting with the angular-ui typeahead directive to create a filtered input box that only shows items based on what has been typed. However, my current code is displaying all the items instead of just the filtered ones. If you'd like ...

Stopping Amazon Web Services Lambda functions from running on their own

I've implemented a Lambda function that is triggered whenever a new folder object is created in the root bucket. A unique identifier is generated for each folder object, such as 67459e53-20cb-4e7d-8b7a-10e4cd165a44 Within the root bucket, there is a ...

Transfer files from another domain using ExpressJs

I am working with a server using nodeJS and expressJS. I have set up a route called /abc where I want to send an HTML file that is stored in a Google Cloud Bucket. Initially, I attempted to use res.sendFile, but it did not work because it only sends files ...

Utilize Lodash to iterate through functions in a loop and retrieve the first matching result

I am looking to iterate through an array of objects and call a method on them. If the result of that method meets certain conditions, I want to immediately return that result. The current implementation is as follows: public getFirstMatch(value: string, a ...

Importing JS files or SDKs in Angular that are not modules

Currently, I am incorporating the Avaya SDK (which consists of 3 JS files) into my Angular project. However, when attempting to import it, I encounter an error stating that it is not recognized as a module. Any suggestions on how to resolve this issue? Th ...

Why is it that when drawing rectangles with HTML 5 canvas using pixel size, a black rectangle appears instead of blue?

My intention was to create a large blue rectangle measuring 320 X 240 pixels on the Canvas in Firefox, but I'm only getting a black rectangle instead. This issue is perplexing as I am simply experimenting with pixel drawing and for some reason, it&apo ...

Is it possible to modify the size of a bullet image in Javascript?

Can an image bullet style loaded via a URL be resized using JavaScript code like this: var listItem = document.createElement('li'); listItem.style.listStyleImage = "url(some url)"; listItem.style.listStylePosition = "inside"; I aim to increase ...

Using jQuery to target the td:nth-child selector inside a document.ready function is not viable

Currently, I am working on a language learning project where I import a table of German words and their English translations from a .csv file using the jQuery.csvToTable plugin. My goal is to replace the words in the cells with an HTML input when the lang ...

Determine the selected option in the dropdown menu upon loading the page and when clicked

I am working on capturing the value of a drop-down list whenever it is changed or when the page loads. The aim is to display different div elements based on the selected option in the report field - either State or Year. Any assistance with this would be ...

Combining React with Leaflet to style a layer is creating a beautiful display of multiple CircleMarkers

Currently, I am working with React and Leaflet to dynamically display CircleMarkers on a map whenever the mouse hovers over a certain div. This particular div contains information about the coordinates of one or more CircleMarkers that I aim to change the ...