1.0.0 • Published 3 years ago

token-authentication-tomsawyer v1.0.0

Weekly downloads
-
License
ISC
Repository
-
Last release
3 years ago

token-authentication

A plug-in unit for token authentication.

Install

$ npm install token-authentication-tomsawyer

Usage

setting.js

        // 过期时间
        signTime: 3600 * 24 * 3,
        // 请求头参数
        header: 'Authorization',
        // 不用校验的路由
        unRoute: [
            { url: '/login', methods: ['POST']},
            { url: '/register', methods: ['POST']}
        ]

app.js

const setting = require('./setting.js')
const tokenverify = require('./tokenverify.js')
// 解析token获取用户信息
app.use((req, res, next) => {
    // 获取请求头中的参数
    let token = req.headers[setting.token.header]
    if (token === undefined) {
        return next()
    } else {
        // token校验并将校验结果保存至请求头中
        tokenverify.getToken(token).then(data => {
            req.data = data
            return next()
        }).catch(_ => {
            return next()
        })
    }
})
//验证token是否过期并规定哪些路由不用验证
app.use(expressJwt({
    secret: setting.token.signKey,
    algorithms: ['HS256']
}).unless({
    //除了这个地址,其他的URL都需要验证
    path: setting.token.unRoute
}))
//当token失效返回提示信息
app.use((err, req, res, next) => {
    if (err.status === 401) {
        return res.status(err.status).json({
            status: err.status,
            msg: 'The token is invalid',
            error: err.name + ':' + err.message
        })
    }
})