JWT 介绍
- 什么是JWT
- JSON WEB TOKEN
- 认证机制
- 原理
- 结构
- 注意点
JWT: JSON WEB TOKEN
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA
认证机制
原理
unsignedToken = encodeBase64Url(header) + '.' + encodeBase64Url(payload)
signature = algorithm(unsignedToken)
JWT = unsignedToken + '.' + signature
结构
- Header
- Payload
- Signature
Header
{
"typ":"JWT",
"alg":"HS256" // 签名算法。
}
Payload
{
“iss”:"jpush", // 签发人
"sub":"auth-server", // 主题
"aud":"cyril", // 接收人
"exp":1523844170761, // 过期时间(重要)
"nbf":1523844070761, // 生效时间
“iat”:1523844070000, // 签发时间
"jti":"7dedcff8d6fb48cf92a01d1ae036dd98", // jti 标识id
}
- 自定义 Claim
{
“key”:"value"
}
Signature
- HASH(encodeBase64Url(header) + '.' + encodeBase64Url(payload), secret)
注意点
- 计算代替存储,时间复杂度换空间复杂度
- 分布式应用减少IO
- 无法对状态进行跟踪, 一旦签发就已经固定
- 主体只经过base64编码,注意不要存放敏感信息
io.jsonwebtoken / jjwt / 0.6.0
// 创建token
String token=Jwts.builder()
.setHeaderParam("typ", "JWT")
.setPayload(JSON.toJSONString(tokenPayload))
.signWith(SignatureAlgorithm.HS256, TOKEN_SECRET_KEY)
.compact();
// 验证token
try {
Jws<Claims> claims = Jwts.parser()
.requireSubject("Joe")
.require("hasMotorcycle", true)
.setSigningKey(key)
.parseClaimsJws(compactJws);
} catch (MissingClaimException e) {
} catch (IncorrectClaimException e) {
} catch (ExpiredJwtException e) {
}