JWT TOKEN issue



我正在开发一个身份验证后端,有点像我正在生成jwt,我需要将其存储在数据库中。

就像我想让用户登录,而不是令牌将生成并存储在cookie中,然后每当用户访问一个秘密页面(需要身份验证才能打开)时,他从该页面发送请求,jwt将验证令牌,但它是否在过期后工作?我需要在数据库中存储JWT吗?

我想知道关于jwt的最佳实践

基本上不需要将jwt令牌存储到数据库中。这不是一个好的做法。

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.
...
})

如果您只开发后端,则不需要在数据库中存储JWT令牌。你只需要生成JWT令牌。前端开发人员从他们那边处理JWT令牌。

最新更新