什么是JSON Web Tokens (JWT)?
1 | JSON Web Token (JWT) is a compact, URL-safe means of representing |
怎么用?
authentication时,当user成功登录,server生成access token, 发送给user;user请求server时带上JWT,server通过JWT验证是否是可信任的客户端请求了。
结构
在客户端看来JWT是一串encode加密过的字符串,header.payload.signature
,如下图左边。但它decode后其实是下图右边的JSON结构体
1. 生成header
e.g.1
2
3
4{
"alg": "HS256",
"typ": "JWT"
}
这里,alg的值指定用HMAC-SHA256算法签名
2. 生成payload
包含用户相关的信息1
2The second part of the token is the payload, which contains the claims.
Claims are statements about an entity (typically, the user) and additional data.
有三种claims: registered, public, and private claims.
e.g.1
2
3
4
5
6
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
3.生成signature
1 |
|
把header跟payload encode结构后,用’.’连接,生成: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ
再用指定的hash算法(例子是HS256),用私钥(服务端的)生成签名:SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
验证
如图1, JWT由Authentication server生成, 在client认证后发给client; client请求application server的时候带上JWT,application server在认证阶段从Authentiation server那儿拿到scret key;用同样算法生成signature, 跟client发来的JWT的signature做比较,看是否match。
5 Easy Steps to Understanding JSON Web Tokens (JWT)
JSON Web Token Introduction - jwt.io
RFC 7519 - JSON Web Token (JWT)
scan qr code and share this article