使用jwt鉴权(jsonwebtoken)

1. 下载jsonwebtoken

npm i -S jsonwebtoken

2. 引用

const jwt = require('jsonwebtoken');

3. 需要设置秘钥

const secretKey = '3.14159263528542852651268541';

4. 设置jwt

const token = await jsonwebtoken.sign(data.dataValues, secretKey, { expiresIn: 60 * 60 * 4 });

5. 验证

await jwt.verify(ctx.headers.authorization, secretKey);

示例

const router = require('koa-router')();
const jwt = require('jsonwebtoken'); // jwt生成token
const keys = '3.1415926.1314.520'
//定义允许直接访问的url
const allowpage = [
    '/api/register'/*注册*/, '/api/login'/*登录*/, '/api/user/sendemail'/*注册发送邮箱*/,
    '/api/sendemail'/* 发送邮箱 */, '/data'/*测试*/,
    '/api/changepass'/*修改密码*/
];
//路由监听,验证token
router.use(async (ctx, next) => {
    let url = ctx.originalUrl
    if (allowpage.indexOf(url) === -1) {
        const token = ctx.header.authorization;
        try {
            await jwt.verify(token, keys);
            await next();
        } catch {
            ctx.body = {
                code: 405,
                msg: '用户登录过期,请重新登录'
            }
        }
    } else {
        await next();
    }
});
module.exports = router;
//鉴权
// ./src/middlewares/auth.js
const jsonwebtoken = require('jsonwebtoken');
const secretKey = '3.14159263528542852651268541'

module.exports = () => {

    return async (ctx, next) => {
        try {
            let user = jsonwebtoken.verify(ctx.headers.authorization, secretKey);
            ctx.state.user = user;
        } catch (err) {
            ctx.throw(401, {
                code: -1,
                message: '你没有登录'
            });
        }
        await next();
    };
}

 

posted @ 2022-11-09 09:03  默永  阅读(229)  评论(0编辑  收藏  举报