如何在koa2和koa2中使用jwt节点js
我有一个用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", {
});
}
})
谢谢。
I have a page written in nodejs and koa, and I'm a little confused about JWT, please check following code.
'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;
I want to implement that when accessing the login page, if the token generated by jwt exists on the server side and is correct, then console.log("logined")
,if not, show the login page.
.get('/', async (ctx, next) => {
//how to verify the token?
if(token) {
console.log("logined");
} else {
await ctx.render("login", {
});
}
})
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
生成令牌后,您应该在用户浏览器中将该令牌设置为 cookie 或其他方式,
然后在请求/页面时检查令牌并验证有效性
After generating the token you should set that token in user's browser as cookie or some other way,
Then while requesting / page check for the token and verify the validity