当前位置: 首页 > 后端技术 > Node.js

songEagle开发系列:在Vue+Vuex+Koa中使用JWT认证

时间:2023-04-03 17:54:34 Node.js

1.前言JWT(JSONWebToken)是一个基于JSON的开放标准(RFC7519)实现,用于在网络环境之间传输声明。JWT并不是什么新鲜事物,网上已经有很多相关的介绍。如果不太了解,可以上网搜索相关资料。同步到sau交流学习社区:https://www.mwcxs.top/page/45...2.源码Talkischeap。给我看代码。3.WorkflowJWT本质上是一个token。前后端建立HTTP连接时都会进行相应的验证。博客后台管理系统发起登录请求,后台服务器验证成功后生成JWT认证信息;前端收到JWT后存储;前端会在每次接口调用发起HTTP请求时,将JWT放入HTTPheaders参数中的授权一并发送给后端;后端收到请求后,会根据JWT中的信息检查当前发起HTTP请求的用户是否有访问权限,如果有访问权限,则交给服务端继续处理。如果没有,直接返回401错误。四、实现过程1、登录成功后生成JWT说明:以下代码只保留核心代码,详细代码可查看对应文件,下同。///server/api/admin/admin.controller.jsconstjwt=require('jsonwebtoken');constconfig=require('../../config/config');exports.login=async(ctx)=>{//...if(hashedPassword===hashPassword){//...//用户令牌constuserToken={name:userName,id:results[0].id};//发行令牌consttoken=jwt.sign(userToken,config.tokenSecret,{expiresIn:'2h'});//...}//...}2。添加中间件验证JWT///server/middlreware/tokenError.jsconstjwt=require('jsonwebtoken');constconfig=require('../config/config');constutil=require('util');constverify=util.promisify(jwt.verify);/***判断token是否可用*/module.exports=function(){returnasyncfunction(ctx,next){try{//getjwtconsttoken=ctx.header.authorization;if(token){try{//解密payload,获取用户名和IDletpayload=awaitverify(token.split('')[1],config.tokenSecret);ctx.user={名称:payload.name,id:payload.id};}catch(err){console.log('tokenverifyfail:',err)}}awaitnext();}catch(err){if(err.status===401){ctx.status=401;ctx.body={success:0,message:'认证失败'};}else{err.status=404;ctx.body={成功:0,消息:'404'};}}}}3.在Koa.js中添加JWT处理这里需要在开发时过滤掉登录界面(login),否则会导致JWT校验永远失败///server/config/koa.jsconstjwt=require('koa-jwt');consttokenError=require('../middlreware/tokenError');//...constapp=newKoa();app.use(tokenError());app.use(bodyParser());app.use(koaJson());app.use(resource(path.join(config.root,config.appPath)));app.use(jwt({secret:config.tokenSecret})。除非({路径:[/^\/backapi\/admin\/login/,/^\/blogapi\//]}));module.exports=app;4.前端处理前端开发使用Vue.js发送HTTP请求使用axios。(1)登录成功后,将JWT存放到localStorage中(可以根据个人需要存放,个人更喜欢存放在localStorage中)。methods:{login:asyncfunction(){//...letres=awaitapi.login(this.userName,this.password);如果(res.success===1){this.errMsg='';localStorage.setItem('SONG_EAGLE_TOKEN',res.token);this.$router.push({path:'/postlist'});}else{this.errMsg=res.message;}}}(2)Vue.js中的路由(routing)在跳转前检查JWT是否存在,不存在则跳转到登录页面。///src/router/index.jsrouter.beforeEach((to,from,next)=>{if(to.meta.requireAuth){consttoken=localStorage.getItem('SONG_EAGLE_TOKEN');if(token&&token!=='null'){next();}else{next('/login');}}else{next();}});(3)在axios拦截器中给HTTP添加Authorization信息///src/api/config.jsaxios.interceptors.request.use(config=>{consttoken=localStorage.getItem('SONG_EAGLE_TOKEN');if(token){//Bearer为JWT认证头信息config.headers.common['Authorization']='Bearer'+token;}returnconfig;},error=>{returnPromise.reject(error);});(4)axios拦截器在收到HTTP返回状态时统一处理返回///src/main.jsaxios.interceptors.response.use(response=>{returnresponse;},error=>{if(error.response.status===401){Vue.prototype.$msgBox.showMsgBox({title:'错误提示',content:'您的登录信息已过期,请重新登录',isShowCancelBtn:false}).then((val)=>{router.push('/login');}).catch(()=>{console.log('取消');});}else{Vue.prototype.$message.showMessage({type:'error',content:'系统错误'});}返回Promise.reject(error);});5。总结这基本上就是JWT过程。当然,纯JWT并不代表绝对安全,但对于个人博客系统的认证来说已经足够了。最后做个小广告。我的个人博客目前正在开发新版本,包括两个部分:[前端](https://github.com/saucxs/son...[后端??](https://github.com/saucxs/son...都已经在GitHub上开源了,功能也在逐步完善中,欢迎有兴趣的同学fork和star。