eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSmFja0RhbiIsImFkbWluIjp0cnVlLCJpYXQiOjE1MzYxMzQxMzcsImV4cCI6NDY5ODM3NDEzN30.yuGHsgfJbg5ArbeVGKJENQOYuBsYFFLDbwiExkPSH_k
{
"alg": "HS256"
}
eyJuYW1lIjoiSmFja0RhbiIsImFkbWluIjp0cnVlLCJpYXQiOjE1MzYxMzQxMzcsImV4cCI6NDY5ODM3NDEzN30
{
"iss": "fengjun.com",
"exp": "145637890",
"name": "JackDan",
"admin": true
}
eyJuYW1lIjoiSmFja0RhbiIsImFkbWluIjp0cnVlLCJpYXQiOjE1MzYxMzQxMzcsImV4cCI6NDY5ODM3NDEzN30
const encodedString = base64UrlEncode(header) + "." + base64UrlEncode(payload);
HMACSHA256(encodedString, 'secret');
yuGHsgfJbg5ArbeVGKJENQOYuBsYFFLDbwiExkPSH_k
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSmFja0RhbiIsImFkbWluIjp0cnVlLCJpYXQiOjE1MzYxMzQxMzcsImV4cCI6NDY5ODM3NDEzN30.yuGHsgfJbg5ArbeVGKJENQOYuBsYFFLDbwiExkPSH_k
cd testWorkspace
mkdir jwt_demo
cd jwt_demo
npm init -y
安装签发与验证JWT的功能包,这里使用的是jsonwebtoken,在项目里面安装这个包。
效果图如下:
package.json
效果图:.js
文件,比如index.js
,在文件里添加下面这些代码:const jwt = require('jsonwebtoken')
// token data token数据
const payload = {
name: 'JackDan',
admin: true
}
// secret 密钥
const secret = 'JUNJUNLOVEFENGFENG'
// 签发 token
const token = jwt.sign(payload, secret, {expiresIn: '36600days'})
// 输出签发的 Token
console.log(token)
jsonwebtoken
里面提供的jwt.sign
功能,去签发一个token。这个sign方法需要三个参数: index.js
这个文件(node index.js),会输出应用签发的token:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSmFja0RhbiIsImFkbWluIjp0cnVlLCJpYXQiOjE1MzYxMzQxMzcsImV4cCI6NDY5ODM3NDEzN30.yuGHsgfJbg5ArbeVGKJENQOYuBsYFFLDbwiExkPSH_k
// header
{
"alg": "HS256",
"typ": "JWT"
}
// payload
{
name: 'JackDan',
admin: true,
iat: 1536134993,
exp: 4698374993
}
// signature
yuGHsgfJbg5ArbeVGKJENQOYuBsYFFLDbwiExkPSH_k
jwt.verify
这个方法去做一下验证。这个方法是Node.js的jsonwebtoken这个包提供的,在其他的应用框架或者系统里,你可能会找到类似的方法来验证JWT。// 验证 Token
jwt.verify(token, secret, (error, decoded) => {
if (error) {
console.log(error.message)
return
}
console.log(decoded)
})
C:\projects\testWorkspace\jwt_demo>node index.js
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSmFja0RhbiIsImFkbWluIjp0cnVlLCJpYXQiOjE1MzYxMzQ5OTMsImV4cCI6NDY5ODM3NDk5M30.ELAlzPGVvjsK0kK1Yl1PArb0wS3860R6c7mqG-5M4eY
{ name: 'JackDan', admin: true, iat: 1536134993, exp: 4698374993 }
C:\projects\testWorkspace\jwt_demo>mkdir config
C:\projects\testWorkspace\jwt_demo>cd config
C:\projects\testWorkspace\jwt_demo\config>ssh-keygen -t rsa -b 2048 -f private.key
C:\projects\testWorkspace\jwt_demo\config>openssl rsa -in private.key -pubout -outform PEM -out public.key
const fs = require('fs')
// 获取签发 JWT 时需要用的密钥
const privateKey = fs.readFileSync('./config/private.key')
jwt.sign
方法,只不过在选项参数里特别说明一下使用的算法是RS256:// 获取验证 JWT 时需要用的公钥
const publickey = fs.readFileSync('./config/public.key')
// 验证 Token
jwt.verify(tokenRS256, publickey, (error, decoded) => {
if (error) {
console.log(error.message)
return
}
console.log(decoded)
})
JackDan Thinking