io.jsonwebtoken
jjwt
0.9.1
Gradle:
dependencies {
compile ‘io.jsonwebtoken:jjwt:0.9.1’
}
public String JWTGenerate() {
Map
map.put(“claim1”, “claim1value”);
map.put(“claim2”, “claim2value”);
String key = Base64.encodeToString(“secret”.getBytes(), 0);
//Key key = MacProvider.generateKey(SignatureAlgorithm.HS256);
Date exp = new Date(System.currentTimeMillis() + 60 * 1000);//过期时间
String compactJws = Jwts.builder().addClaims(map).setHeaderParam(“typ”, “JWT”)
.signWith(SignatureAlgorithm.HS256, key).setExpiration(exp).compact();
try {
Jwts.parser().setSigningKey(key).parseClaimsJws(compactJws);
//OK, we can trust this JWT
} catch (SignatureException e) {//don’t trust the JWT!
e.printStackTrace();
} catch (ExpiredJwtException e) {//The key is expiration
e.printStackTrace();
}
return compactJws;
}
先看一下使用上面的"jjwt"库如何进行解码操作:
public void JWTParse(String jwt) {
String key = Base64.encodeToString(“secret”.getBytes(), 0);
//Key key = MacProvider.generateKey(SignatureAlgorithm.HS256);
//在解析的时候一定要传key进去,否则无法通过key的认证
Jwt parse = Jwts.parser().setSigningKey(key).parse(jwt);
Header header = parse.getHeader();
Map
String param = (String) map.get(“param”);
}
另外还可以使用其它的库,可前往 https://github.com/auth0/JWTDecode.Android 进行学习和使用,当然,你也可以用上面提到的Java库来进行解码。
添加依赖:
compile ‘com.auth0.android:jwtdecode:1.1.1’
使用:
String token = “eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ”;
JWT jwt = new JWT(token);
/**
*/
//Returns the Issuer value or null if it’s not defined.
String issuer = jwt.getIssuer();
//Returns the Subject value or null if it’s not defined.
String subject = jwt.getSubject();
//Returns the Audience value or an empty list if it’s not defined.
List audience = jwt.getAudience();
//Returns the Expiration Time value or null if it’s not defined.
Date expiresAt = jwt.getExpiresAt();
//Returns the Not Before value or null if it’s not defined.
Date notBefore = jwt.getNotBefore();
//Returns the Issued At value or null if it’s not defined.
Date issuedAt = jwt.getIssuedAt();
//Returns the JWT ID value or null if it’s not defined.
String id = jwt.getId();
//Time Validation
boolean isExpired = jwt.isExpired(10); // 10 seconds leeway
/**
*/
Claim claim = jwt.getClaim(“isAdmin”);
我这里整理了一份完整的学习思维以及Android开发知识大全PDF,有需要的同学可以自行领取。
资料获取方式:Android完整知识学习体系路线
当然实践出真知,即使有了学习线路也要注重实践,学习过的内容只有结合实操才算是真正的掌握。
7/blob/master/Android%E5%BC%80%E5%8F%91%E4%B8%8D%E4%BC%9A%E8%BF%99%E4%BA%9B%EF%BC%9F%E5%A6%82%E4%BD%95%E9%9D%A2%E8%AF%95%E6%8B%BF%E9%AB%98%E8%96%AA%EF%BC%81.md)**
当然实践出真知,即使有了学习线路也要注重实践,学习过的内容只有结合实操才算是真正的掌握。