JSON Web Token(JWT)是一个开放标准(RFC 7519),它定义了一种紧凑且独立的方式,可以在各方之间作为JSON对象安全地传输信息。此信息可以通过数字签名进行验证和信任。JWT可以使用秘密(搭配HMAC算法)或使用RSA或ECDSA的公钥/私钥对进行签名。多用于无状态的身份认证(无状态指服务端不会持久化token).
{
"typ": "JWT",
"alg": "HS256"
}
{
"iss": "Online JWT Builder",
"iat": 1416797419,
"exp": 1448333419,
"aud": "www.gusibi.com",
"sub": "uid",
"nickname": "goodspeed",
"username": "goodspeed",
"scopes": [ "admin", "user" ]
}
iss: 该JWT的签发者,是否使用是可选的;
sub: 该JWT所面向的用户,是否使用是可选的;
aud: 接收该JWT的一方,是否使用是可选的;
exp(expires): 什么时候过期,这里是一个Unix时间戳,是否使用是可选的;
iat(issued at): 在什么时候签发的(UNIX时间),是否使用是可选的;
nbf (Not Before):如果当前时间在nbf里的时间之前,则Token不被接受;一般都会留一些余地,比如几分钟;,是否使用是可选的;
jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击。
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
package com.tanmibo.study.mystudynotes.JWTtest;
import org.apache.tomcat.util.codec.binary.Base64;
import org.bouncycastle.crypto.RuntimeCryptoException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
public class JWTtest {
private static String encrytSHA256(String content, String secret) {
try {
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
byte[] keyBytes = secret.getBytes("UTF-8");
hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256"));
String sign = new String(Base64.encodeBase64(hmacSha256.doFinal(content.getBytes("UTF-8")),true));
return sign;
} catch (Exception e) {
throw new RuntimeCryptoException("加密异常");
}
}
public static void main(String[] args) {
String header = "{\"typ\":\"JWT\",\"alg\":\"HS256\"}";
System.out.println("header BASE64URL加密后:"+Base64.encodeBase64String(header.getBytes()));
String payload = "{\"exp\":1533192702,\"username\":\"tanmb\"}";
System.out.println("payload BASE64URL加密后:"+Base64.encodeBase64String(payload.getBytes()));
String secret = "dvjM9xT3zWUzqtr4";
String message = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9." +
"eyJleHAiOjE1MzMxOTI3MDIsInVzZXJuYW1lIjoidGFubWIifQ";
//(HMAC计算返回原始二进制数据后进行Base64编码)
String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9." +
"eyJleHAiOjE1MzMxOTI3MDIsInVzZXJuYW1lIjoidGFubWIifQ." +
"wwS4uSjq0_HBd-7QFO0EzyEC7IF_4DQszxxYZFpZG4k";
System.out.println("sign为前两者加盐值HMAC计算返回原始二进制数据后进行Base64编码:");
System.out.println(encrytSHA256(message,secret));
System.out.println("token为:");
System.out.println(token);
}
}
header BASE64URL加密后:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9
payload BASE64URL加密后:eyJleHAiOjE1MzMxOTI3MDIsInVzZXJuYW1lIjoidGFubWIifQ==
sign为前两者加盐值HMAC计算返回原始二进制数据后进行Base64编码:
wwS4uSjq0/HBd+7QFO0EzyEC7IF/4DQszxxYZFpZG4k=
token为:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MzMxOTI3MDIsInVzZXJuYW1lIjoidGFubWIifQ.wwS4uSjq0_HBd-7QFO0EzyEC7IF_4DQszxxYZFpZG4k
!! 其中JWT包中对/ =等字符做过处理
try {
Algorithm algorithm = Algorithm.HMAC256("secret");
String token = JWT.create()
.withIssuer("auth0")
.sign(algorithm);
} catch (JWTCreationException exception){
//Invalid Signing configuration / Couldn't convert Claims.
}
RSAPublicKey publicKey = //Get the key instance
RSAPrivateKey privateKey = //Get the key instance
try {
Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);
String token = JWT.create()
.withIssuer("auth0")
.sign(algorithm);
} catch (JWTCreationException exception){
//Invalid Signing configuration / Couldn't convert Claims.
}
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE";
try {
Algorithm algorithm = Algorithm.HMAC256("secret");
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
} catch (JWTVerificationException exception){
//Invalid signature/claims
}
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE";
RSAPublicKey publicKey = //Get the key instance
RSAPrivateKey privateKey = //Get the key instance
try {
Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
} catch (JWTVerificationException exception){
//Invalid signature/claims
}
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE";
try {
DecodedJWT jwt = JWT.decode(token);
} catch (JWTDecodeException exception){
//Invalid token
}
String algorithm = jwt.getAlgorithm(); //获取加密算法
String type = jwt.getType(); //获取类型
String contentType = jwt.getContentType();
String keyId = jwt.getKeyId();
私人声明
Claim claim = jwt.getHeaderClaim("owner");
Issuer ("iss")->发行人
String issuer = jwt.getIssuer();
Subject ("sub")->主题
String subject = jwt.getSubject();
Audience ("aud")->观众
List audience = jwt.getAudience();
Expiration Time ("exp")->到期时间
Date expiresAt = jwt.getExpiresAt();
Not Before ("nbf")->在....之前不
Date notBefore = jwt.getNotBefore();
Issued At ("iat")->发行于....
Date issuedAt = jwt.getIssuedAt();
JWT ID ("jti")
String id = jwt.getId();
私人声明
Map claims = jwt.getClaims();
//Key is the Claim name
Claim claim = claims.get("isAdmin");
//或者
Claim claim = jwt.getClaim("isAdmin");
附:
java-jwt包传送门
我的GitHub同性交友首页tanmibo.github.io