koa里使用jwt

1.安装jsonwebtoken

npm install jsonwebtoken

2.获取token,sign.js

先不加身份验证了,只是简单生成一个token

复制代码
const jwt = require('jsonwebtoken');
async function getToken(ctx) {
    ctx.response.type = 'json';
    ctx.status = 200;
    const secret = 'ABCDEFG';
    const token = jwt.sign({
        data: 'XYZ',
    }, secret, {
        expiresIn: 60 // 过期时间
    });
    ctx.cookies.set(
        'token',
        token, {
            domain: 'localhost', // 设置 cookie 的域
            path: '/', // 设置 cookie 的路径
            maxAge: 60 * 1000, // cookie 的有效时间 ms
            httpOnly: true, // 是否要设置 httpOnly
            overwrite: true // 是否要覆盖已有的 cookie 设置
        }
    )
    ctx.body = {
        success: true,
        token: `Bearer ${token}`,
    };
}

module.exports = {
    'getToken': getToken,
}
复制代码

3.验证token, verify.js

复制代码
const jwt = require('jsonwebtoken');
const verifyToken = async (ctx, next) => {
    let flag = false;
    const secret = 'ABCDEFG';
    try {
        let url = ctx.request.url.split('?')[0]
         // 检测接口是否在不校验接口列表中
        let url_config = [
            '/api/getToken'
        ]
        let checkUrl = url_config.some((item) => {
            return item == url
        })

        if (checkUrl) {
            await next()
        } else {
            let token = ctx.request.headers["authorization"]
            token = token.replace('Bearer ', '')
            if (token) {
                let playload = await jwt.verify(token, secret)
                const {
                    data
                } = playload;
                if (data === 'XYZ') {
                    await next()
                }
            } else {
                ctx.body = {
                    code: 1000,
                    msg: '登录信息已过期'
                }
            }
        }
    } catch (error) {
         if (error.name == 'TokenExpiredError') {
             ctx.body = {
                 code: 401,
                 msg: 'token已过期'
             }
         } else if (error.name == 'JsonWebTokenError') {
             ctx.body = {
                 code: 401,
                 msg: '无效的token'
             }
         } else {
             ctx.body = {
                 "error": {
                     "type": "FAILED",
                     "message": "未知",
                 }
             }
         }
    }
}
module.exports = {
    'verifyToken': verifyToken,
}
复制代码

4.路由 router.js

复制代码
const Router = require('koa-router')
const router = new Router({
    prefix: '/api', // 统一前缀,接口全部为 /api/xxx 格式
})
const {
    verifyToken
} = require('./verify')
router.use(verifyToken)
const sign = require('./sign');
Object.keys(sign).forEach(key => {
    router.all("/" + key, sign[key]);
})

const test = require('./test');
Object.keys(test).forEach(key => {
    router.all("/" + key, test[key]);
})

module.exports = router;
复制代码

5.测试test.js

复制代码
async function getNews(ctx) {
    ctx.response.type = 'json';
    ctx.status = 200;
    ctx.body = JSON.stringify({
        success: true,
        content: [{
                id: "1",
                title: "news1",
                content: "new11111111"
            },
            {
                id: "2",
                title: "news2",
                content: "new222222"
            },
            {
                id: "3",
                title: "news3",
                content: "new333333"
            },

        ],
    });
}

module.exports = {
    'getNews': getNews,
}
复制代码

6.入口app.js

复制代码
const koa = require('koa')
const app = new koa()
const router = require('./router');
app.use(router.routes()).use(router.allowedMethods())
// 启动服务
let port = process.env.PORT || 3005
app.listen(port, () => {
    console.log(`server runing at ${port}...`)
})
复制代码

运行node app.js

使用postman请求

 先获取token

 再在headers里添加 Authorization,把上一个请求获取的token加上,就可以获取数据了

 

posted @   慕尘  阅读(204)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2019-06-13 windows下Java调用可执行文件
点击右上角即可分享
微信分享提示