Token在计算机身份认证中是token(临时)的意思,在词法分析中是token的意思。一般我们所说的token多是指用于认证的token。代币的特点是随机的、不可预测的、时间敏感的、无状态的和可扩展的。跨域基于Token的认证场景。客户端使用用户名和密码请求登录服务器。请求验证是否登录成功。验证成功后,服务端会返回一个Token给客户端。反之,则返回认证失败的信息。客户端收到Token后,会以一种方式存储Token(cookie/localstorage/sessionstorage/others),当客户端发起请求时,选择将Token发送给服务端。服务器收到请求后,验证Token的合法性。如果合法,则返回客户端需要的数据。否则,返回验证失败的信息。Token认证实现——jsonwebtoken先安装第三方模块jsonwebtokennpminstalljsonwebtokenconstexpress=require('express')constpath=require('path')constapp=express();constbodyParser=require('body-parser');constjwt=require('jsonwebtoken');app.use(bodyParser.urlencoded({extended:false}));app.use(express.static(path.join(__dirname,'/')));app.all('*',function(req,res,next){res.header("Access-Control-Allow-Origin","*");res.header("Access-Control-Allow-Headers","Content-Type,Content-Length,Auth,Accept,X-Requested-With");res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");res.header("X-幂ed-By",'3.2.1')??if(req.method=="OPTIONS"){res.sendStatus(200);/*让选项请求快速返回*/}else{next();}});app.get('/createtoken',(request,response)=>{//生成token主体信息letuser={username:'admin',}//这是加密后的密钥(key)letsecret='dktoken';//生成Tokenlettoken=jwt.sign(user,secret,{'expiresIn':60*60*24//设置过期时间,24小时})response.send({status:true,token});})app.post('/verifytoken',(request,response)=>{//这是加密后的密钥(key),必须和生成token时的一样letsecret='dktoken';lettoken=request.headers['auth'];if(!token){response.send({status:false,message:'tokencannotbeempty'});}jwt.verify(token,secret,(错误,结果)=>{if(error){response.send({status:false});}else{response.send({status:true,data:result});}})})app.listen(88)前面-endajaxrequestWhenincludingTokenajaxintherequestheaderjQueryarticle$.ajax({url:'verifytoken',type:'post',headers:{"auth":'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTIzNTQwNjY5LCJleHAiOjE1MjM2MjcwNjl9.ddkS5XEiMzvNQsk9UlMPhyxPSq5S_oh3Nq19eIm9AJU'},success:function(res){console.log(res)}})ajax请求之XMLHttpRequest篇varxhr=newXMLHttpRequest();xhr.open("POST","verifytoken");xhr.setRequestHeader('auth','eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNTIzNTQwNjY5LCJleHAiOjE1MjM2MjcwNjl9.ddkS5XEiMzvNQsk9UlMPhyxPSq5S_oh3Nq19eIm9AJU');xhr.send();ajax请求之axios篇importaxiosfrom'axios'axios({url:url,params:_params||{},headers:{auth:window.sessionStorage.getItem('dktoken')}}).then(res=>{if(!res.data.status&&res.data.error=="unauthorized"){router.push('login');returnfalse;}resolve(res)}).catch(error=>{reject(error)})ajax请求之超级代理篇从'superagent'http.pos导入httpt(getUrl(path)).set('Content-Type','application/x-www-form-urlencoded;charset=UTF-8').set('auth',window.localStorage.getItem('access_token')).end((err,res)=>{});
