JWT在Java和Android中的使用(2)

/**

  • Payload Claims

*/

//Returns the Issuer value or null if it’s not defined in the Payload.

String issuer = jwt.getIssuer();

//Returns the Subject value or null if it’s not defined in the Payload.

String subject = jwt.getSubject();

//Returns the Audience value or null if it’s not defined in the Payload.

List audience = jwt.getAudience();

//Returns the Expiration Time value or null if it’s not defined in the Payload.

Date expiresAt = jwt.getExpiresAt();

//Returns the Not Before value or null if it’s not defined in the Payload.

Date notBefore = jwt.getNotBefore();

//Returns the Issued At value or null if it’s not defined in the Payload.

Date issuedAt = jwt.getIssuedAt();

//Returns the JWT ID value or null if it’s not defined in the Payload.

String id = jwt.getId();

//Private Claims

Claim claim2 = jwt.getClaim(“isAdmin”);

} catch (JWTDecodeException exception){

//Invalid token

}

}

三、JWT在Android中的使用

最初我在安卓中也使用的上面的Java库,但发现在使用org.apache.commons.codec.binary.Base64时会与Android系统中的包出现冲突,自己尝试封装了一下并改了包名,可以成功调用,但这显然不是最好的方案。所以我在这里使用到另外一个库。我们在https://jwt.io/主页上找到Java项目的入口,我在这里选择的是"maven: io.jsonwebtoken / jjwt / 0.9.0",点击该项右下角的"View Repo"按钮即可跳转到项目Github主页进行导入。下面简单说明一下依赖库的方式。

Maven:

io.jsonwebtoken

jjwt

0.9.1

Gradle:

dependencies {

compile ‘io.jsonwebtoken:jjwt:0.9.1’

}

1.JWT生成

public String JWTGenerate() {

Map<String, Object> map = new HashMap<>();

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;

}

2.JWT解码

先看一下使用上面的"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, Object> map = (Map<String, Object>) parse.getBody();

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);

/**

  • Registered Claims

*/

//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

/**

  • Private Claims

*/

Claim claim = jwt.getClaim(“isAdmin”);

四、遇到的问题及其处理方案

在AndroidStudio编译的时候会遇到这样一个问题:

这里写图片描述

解决方案为:

在Module的build.gradle中的android{}中添加下面代码:

packagingOptions {

exclude ‘META-INF/LICENSE’

尾声

对于很多初中级Android工程师而言,想要提升技能,往往是自己摸索成长,不成体系的学习效果低效漫长且无助。 整理的这些架构技术希望对Android开发的朋友们有所参考以及少走弯路,本文的重点是你有没有收获与成长,其余的都不重要,希望读者们能谨记这一点。

最后想要拿高薪实现技术提升薪水得到质的飞跃。最快捷的方式,就是有人可以带着你一起分析,这样学习起来最为高效,所以为了大家能够顺利进阶中高级、架构师,我特地为大家准备了一套高手学习的源码和框架视频等精品Android架构师教程,保证你学了以后保证薪资上升一个台阶。

  • 思维脑图
  • 性能优化学习笔记


  • 性能优化视频

    当你有了学习线路,学习哪些内容,也知道以后的路怎么走了,理论看多了总要实践的。
    《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
    1714762776336)]

[外链图片转存中…(img-m5xy4SWp-1714762776338)]
[外链图片转存中…(img-eA8xB4Ja-1714762776340)]

  • 性能优化视频
    [外链图片转存中…(img-RWdB9C7v-1714762776342)]
    当你有了学习线路,学习哪些内容,也知道以后的路怎么走了,理论看多了总要实践的。
    《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
  • 25
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值