node生成token与验证token(typeScript语法)

12 篇文章 1 订阅

1、首先安装jsonwebtoken

(c)npm install jsonwebtoken -S

2、根据前端发送的登录信息,生成对应token

import { Router,Request,Response } from "express";
import jwt from 'jsonwebtoken';

export default (router:Router) => {
    router.post('/',(req:Request,res:Response) => {
        /* 
        req.body    加密的token信息这里是{user:admin,pass:admin}
        'Agwenbi'   加密的密钥,自己约定
        expiresIn   过期时间,单位秒
        */
        const token = jwt.sign({
            ...req.body
        },'Agwenbi',{
            expiresIn: (60 * 60 * 24) * 7//7天有效期
        });
        res.status(200).json({//token信息发送给前端
            code:0,
            msg:'请求成功',
            token
        });
    });
    return router;
}
//前端接收到token并保存token信息
localStorage.setItem('xmds-token',loginResult.token);

3、前端请求头默认加上token信息

import axios,{AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios';
import qs from 'qs';

class CreateAxios {
    public http:AxiosInstance
    constructor(){
        this.http = axios.create({
            timeout:10 * 1000,
            baseURL:'http://localhost:8090'
        });
    }
}

class AxiosReq extends CreateAxios {//请求拦截器
    constructor(){
        super();
        this.axiosReq();
    }
    axiosReq(){
        this.http.interceptors.request.use((config:AxiosRequestConfig) => {
            const token = localStorage.getItem('xmds-token');
            if(token){//存在token,默认加上token
                config.headers.common['Authorization'] = token;
            }
            if(config.method === 'post'){
                config.data = qs.stringify(config.data);
            }
            return config;
        },error => {
            console.log(error);
        })
    }
}

class AxiosRes extends AxiosReq {//响应拦截器
    constructor(){
        super();
        this.axiosRes();
    }
    axiosRes(){
        this.http.interceptors.response.use((response:AxiosResponse<any>) => {
            const result = Promise.resolve(response.data);
            return result;
        },error => {
            console.log(error);
        })
    }
}

const http:AxiosInstance = new AxiosRes().http;
export default http;

4、node全局路由,验证token

import jwt from 'jsonwebtoken';
const noTokenUrl = ['/login'];//不需要验证token的请求
app.use((req:Request,res:Response,next:NextFunction) => {
    const token = req.headers.authorization;
    if(token){//存在token
        jwt.verify(token,'Agwenbi',(error,decoded) => {//Agwenbi表示密钥,参考第二步设置的密钥
            const tokenFlag = error?.name;
            if(tokenFlag === 'TokenExpiredError'){//token过期
                res.status(200).json({
                    code:401,
                    msg:'token过期'
                });
            }else if(tokenFlag === 'JsonWebTokenError'){//token验证失败
                res.status(200).json({
                    code:401,
                    msg:'无效token'
                });
            }else{//token未过期,且验证通过
                next();
            }
        });
    }else{//不存在token
        if(noTokenUrl.includes(req.url)){//是否在不需要token验证的路由下
            next();
        }else{//不在接受的路由当中,且未携带token
            res.status(200).json({
                code:401,
                msg:'无效token'
            });
        }
    }
});

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Agwenbi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值