Use NodeJs realization of JWT login authentication token

Advantages token authentication login: stateless, cross-domain, you can prevent csrf, good performance (not every request to the appropriate server query session), clients only need to deposit a local token, each time you access the server headers plus the token can

Implementation:
Installation jwtnpm install jsonwebtoken --save

Import packages:const jwt=require('jsonwebtoken')

Basic use:

const jwt=require('jsonwebtoken')
let token = jwt.sign({user: '1234'}, 'Fizz', {expiresIn: 60 * 60})
console.log(token)
   
   
jwt.verify(token, 'Fizz', function (err, data) {
if (err) console.log(err)
else console.log('解析的数据', data)
})

Practical application:

Package token creation and verification:

const jwt=require('jsonwebtoken')
const screat='frdyhdrustgsdt'

function createToken(payload){
	//产生token
	payload.ctime=Date.now()  //创建时间
	//可加其他字段
	return jwt.sign(payload,screat,{expiresIn: 60})   //设置过期时间60s
}

//验证token
function checkToken(token){
	return new Promise((resolve,reject)=>{
		jwt.verify(token,screat,(err,data)=>{
			console.log(data)
			if(err)  reject('token 验证失败')
			else   resolve(data)
			
		})
	})
}
 
module.exports={
	createToken,checkToken
}

JWT client receives the server returns, which can be stored in Cookie, can also be stored in localStorage.

User login is successful return token:

 let token=jwt.createToken({id:data.id,name:data.name})
 res.status(200).send({success:"true",token:token, msg: "登录成功"})

Note that:
Payload is part of a JSON object, used to store the actual data transfer is required. JWT provides for seven official field: the default is not encrypted, anyone can read, do not put confidential information in this section. Also translated into strings using Base64URL algorithm .
Can check out the official https://www.npmjs.com/package/jsonwebtoken#token-expiration-exp-claim

After a successful login, the client other operations, the request to carry on the token, server-side validation:

//检查token
app.use((req,res)=>{
		let token=req.headers.authorization
	jwt.checkToken(token)  
	  .then((data)=>{
	  	console.log(data)
	  next()
	  })
	  .catch((err)=>{
	  	res.send({err:-1,msg:"'token非法"})
	  })
})
Published 41 original articles · won praise 3 · Views 4570

Guess you like

Origin blog.csdn.net/fesfsefgs/article/details/104281914