NodeJs实践JSON Web Token
JWT简介
参考
http://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html
https://github.com/auth0/node-jsonwebtoken#readme
http://www.suoniao.com/article/41059
////////////////
// 参考
// http://www.ruanyifeng.com/blog/2018/07/json_web_token-tutorial.html
// https://github.com/auth0/node-jsonwebtoken#readme
// http://www.suoniao.com/article/41059
////////////////
const jwt = require('jsonwebtoken');
const fs = require('fs');
const getConfig = require('../../config/index');
const { TokenException } = require('../lib/HttpException');
class Jwt {
constructor() {
this.Config = getConfig()
}
createToken(userId) {
const cert = fs.readFileSync(this.Config.secret.RSA_PRIVATE_KEY);
const expiresIn = this.Config.secret.expirationTime;
return new Promise((resolve) => {
jwt.sign({
userId,
}, cert, { algorithm: "RS256", expiresIn: expiresIn }, (err, data) => {
if (err) new TokenException(err);
resolve(data)
});
})
}
verifyToken(token) {
const cert = fs.readFileSync(this.Config.secret.RSA_PUBLIC_KEY);
return new Promise((resolve, reject) => {
jwt.verify(token, cert, { algorithm: "RS256" }, (err, data) => {
if (err) new TokenException(err);
resolve(data)
});
})
}
}
本文介绍了如何在Node.js环境中使用JSONWebToken(JWT)进行身份验证。通过引入jsonwebtoken库,展示了如何创建和验证JWT,包括使用RSA密钥对进行签名。文章还提供了在线生成公钥私钥的参考链接,确保了JWT的安全性。
1569

被折叠的 条评论
为什么被折叠?



