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

Node.js使用token进行认证的简单例子

时间:2023-04-03 18:25:29 Node.js

本文只介绍简单的应用。jsonwebtoken的具体介绍和原理可以参考阮一峰老师的JSONWebToken入门教程。使用的Node框架是koa2,前端使用axios发送ajax请求。首先创建项目目录:如何初始化一个Koa2项目我在另一篇文章中有详细介绍,这里不再赘述。然后安装必要的依赖:"dependencies":{"@koa/router":"^8.0.8","ejs":"^3.1.3","jsonwebtoken":"^8.5.1","koa":"^2.12.0","koa-bodyparser":"^4.3.0","koa-jwt":"^4.0.0","koa-static":"^5.0.0","koa-views":"^6.2.2"}在server.js中添加代码以创建一个简单的后端程序:constkoa=require('koa');constapp=newkoa();constbodyParser=require('koa-bodyparser');constrouter=require('@koa/router')();constviews=require('koa-views');conststatic=require('koa-static');constpath=require('path');app.use(bodyParser());app.use(views(__dirname+'/views',{map:{html:'ejs'}}));app.use(static(path.join(__dirname,'/static')));router.get('/',ctx=>ctx.render('index'));app.use(router.routes()).use(router.allowedMethods());app.listen(8080,()=>{console.log('服务器正在8080端口运行');});在constpath=require('path');之后添加代码:const{sign}=require('jsonwebtoken');constsecret='demo';constjwt=require('koa-jwt')({secret});sign方法用于生成toekn,secret是自定义秘钥,jwt提供道路访问控制的功能,会检查需要限制的资源请求,创建路由login:router.post('/login',ctx=>{const{user}=ctx.request.body;if(user&&user.username==='vip'){let{username}=user;consttoken=sign({username},secret,{expiresIn:'1h'});ctx.body={message:'GETTOKENSUCCESS',status:200,token}}else{ctx.body={message:'GETTOKENFAILED',status:500}}});如代码所示,当前端发送的请求体中包含用户对象,用户名为vip时,会生成一个token返回给前端。这里使用了上面提到的sign方法。第一个参数是用户信息,第二个参数是自定义key,第三个参数是option,这里只定义过期时间。然后创建路由信息:router.get('/info',jwt,ctx=>{ctx.body={message:`Welcome${ctx.state.user.username}!`};});和往常一样的路由代码略有不同。这里添加一个jwt中间件来控制权限。如果认证失败,则不会执行下面的代码。上面生成token后,用户名会存储在ctx.state.user中,这里可以直接获取。此时在控制台输入nodeserver启动项目,打开index.html文件,添加一个简单的表单和一个按钮,引入axios:

提交获取首先添加登录逻辑:document.querySelector('#submit').addEventListener('click',e=>{e.preventDefault();constusername=document.querySelector('input[name="username"]')。value;axios.post('/login',{user:{username}}).then(response=>{response=response.data;const{status,token,message}=response;if(status===200){localStorage.setItem('token',token);}alert(message);}).catch(error=>alert(error.toString()));});这里将服务端生成的token保存在localStorage中,以备下次使用。当在输入框中输入vip并点击提交按钮,后端返回如下格式的信息:message:"GETTOKENSUCCESS"status:200token:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InZpcCIsImlhdCI6MTU5MDMyOTkxOSwiZXhwIjoxNTkwMzMzNTE5fQ.PsyLYmr-pDxxdtrBEvMccVtBr9-xtOAHdZKen4FP34c"然后再添加获取逻辑:document.querySelector('#get').addEventListener('click',e=>{e.preventDefault();constinstance=axios.create({headers:{authorization:`Bearer${localStorage.getItem('token')}`}});instance.get('/info').then(response=>{response=response.data;console.log(response)alert(response.message);}).catch(error=>alert(error.toString()));});Theaxios.createmethodisusedhere,whichcanaddtokeninformationintherequestheader.UselocalStoragetogetthetokenandspellitintoaformlikeauthorization:Bearertoken,andthenusetheexampletosendthegetrequest.Atthistime,clicktheGetbuttonagain,anditwillprompt:Provethatthetokenisvalid.Atthistime,gototheApplicationtoclearthelocalStoragerecord,andthenclicktheGetbutton,andtheprompt:Provethattheinterceptionwassuccessful.YoucangotomyGitHubtoviewanddownloadthecompleteexample.Ifyouhaveanyquestions,pleaseleaveamessagetodiscuss.