Home > Mobile >  JWT TOKEN issue
JWT TOKEN issue

Time:12-23

Hi guys i am developing a authentication backend and confused a bit like if i am generating the jwt do i need to store it in database.

Like i want to the user to get signed in than a token will generate and than stores in cookies and than whenever the user visits a secret page (need authentication to open) he send a request from that page and jwt will verify the token but does it work after expiration or not? and do i need to store the jwt in database?

I want to know about the best practices for jwt

CodePudding user response:

Basically you don't need to store jwt token into database. It is not a good practice.

const express = require("express")

const jwt = require("jsonwebtoken")

const app = express()

const jwt_secret = 'some_secret_text'

app.post('/generate-token', (req, res) => {

// user id will be the _id of that user in database

  const token = jwt.sign({ userID: "userID" }, jwt_secret,{expiresIn : '12h'})
  
 res.writeHead(200, {
   "Set-Cookie": `token=${token}`,
   "Content-Type": `application/json`,
 })
  
  res.json({message : "message"})

})

// cookie parser

function parseCookies (request) {

const list = {};

const cookieHeader = request.headers?.cookie;
if (!cookieHeader) return list;

cookieHeader.split(`;`).forEach(function(cookie) {
    let [ name, ...rest] = cookie.split(`=`);
    name = name?.trim();
    if (!name) return;
    const value = rest.join(`=`).trim();
    if (!value) return;
    list[name] = decodeURIComponent(value);
});

return list;
}

// validate token

app.post('/validate-token', (req, res) => {
  ...

  const cookie = parseCookie(req);

  const verified = jwt.verify(cookie.token, jwtSecretKey,{expiresIn : '12h'});

// It returns false if it is expired or not valid

// It returns the object containing userid if it is valid. You can perform some operations with that userid in database.
  ...
})

CodePudding user response:

you dont need to store JWT token in database, if you are developing backend only. u just need to generate the JWT token. front-end developer handle the JWT token from them side.

  • Related