我有一個用 nodejs 和 koa 撰寫的頁面,我對 JWT 有點困惑,請檢查以下代碼。
'use strict';
const Router = require("koa-router");
const router = new Router({prefix: '/login'});
const jwt = require('jsonwebtoken');
const jwtkey = "123456";
router
.get('/', async (ctx, next) => {
await ctx.render("login", {
});
})
.post('/', async (ctx, next) => {
try {
let email = ctx.request.body.email || "";
let password = ctx.request.body.password || "";
//check user
if (islogin) {
let payload = {
email: email,
password: sha1(password).toString()
}
let token = jwt.sign(payload, jwtkey, {expiresIn: '3h'});
ctx.body = {"error": false, "msg": token};
} else {
throw "Wrong";
}
} catch (e) {
ctx.body = {error:true, msg: e instanceof Error ? e.message : e};
}
})
module.exports = router;
我想實作在訪問登錄頁面時,如果jwt生成的token在服務器端存在并且正確,那么console.log("logined"),如果不存在,則顯示登錄頁面。
.get('/', async (ctx, next) => {
//how to verify the token?
if(token) {
console.log("logined");
} else {
await ctx.render("login", {
});
}
})
謝謝你。
uj5u.com熱心網友回復:
生成令牌后,您應該在用戶的瀏覽器中將該令牌設定為 cookie 或其他方式,
然后在請求/頁面檢查令牌并驗證有效性
var decoded = jwt.verify(token, key);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/430858.html
下一篇:詹金斯:無法在初始運行時訪問工件
