java jwt payload_Java JWT做登录认证

本文展示了如何使用Java和JWT库创建及验证JWT令牌。代码创建了一个JWT,包含自定义的header和payload数据,并设置了过期时间。同时,还提供了验证JWT有效性的方法。
摘要由CSDN通过智能技术生成

1 packagecom.drz.proxy.internetProxy.util;2

3 importjava.util.Date;4 importjava.util.HashMap;5 importjava.util.Map;6

7 importorg.apache.commons.codec.binary.Base64;8 importorg.apache.commons.codec.binary.StringUtils;9

10 importcom.auth0.jwt.JWT;11 importcom.auth0.jwt.JWTVerifier;12 importcom.auth0.jwt.algorithms.Algorithm;13 importcom.auth0.jwt.exceptions.JWTCreationException;14 importcom.auth0.jwt.exceptions.JWTVerificationException;15 importcom.auth0.jwt.interfaces.DecodedJWT;16

17 /**

18 * JWT token串结构: header.payload.signature19 * signature=HMACSHA256(base64UrlEncode(header) + "." +base64UrlEncode(payload),Secret)20 *21 * token保存在客户端,每次请求传到后端,服务端只保留密钥,不要把密钥放在header和payload中;22 *23 * header中默认传递参数:24 * {"typ":"JWT","alg":"HS256"}25 *26 * payload官方定义包含属性如下(非强制):27 * iss: jwt签发者28 * sub: jwt所面向的用户29 * aud: 接收jwt的一方30 * exp: jwt的过期时间,这个过期时间必须要大于签发时间31 * nbf: 定义在什么时间之前,该jwt都是不可用的.32 * iat: jwt的签发时间33 * jti: jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击。34 * payload 自定义数据:存放我们想放在token中存放的key-value值35 */

36 public classJWTUtil {37

38 /**

39 * 过期时间40 */

41 private static final long EXPIRE_TIMEMILLS = 6000;42

43 /**

44 * jwt 密钥45 */

46 private static final String SECRET = "jwt_secret";47

48 public staticString create() {49 try{50 Algorithm algorithm =Algorithm.HMAC256(SECRET);51

52 Map headerMap = new HashMap();53 headerMap.put("date", "2022-01-01 18:00");54 headerMap.put("where", "城东小树林");55 String token = JWT.create().withHeader(headerMap)//可自定义传递参数56 //.withIssuer("auth0")//签发者

57 .withIssuedAt(new Date())//签发时间

58 .withSubject("subject").withAudience("100102134")59 .withExpiresAt(new Date(System.currentTimeMillis() +EXPIRE_TIMEMILLS))60 //payload中加入自定义数据

61 .withClaim("name", "小明").withClaim("introduce", "TTT").sign(algorithm);62 System.out.println("当前时间:" + newDate());63 System.out.println("jwt token:" +token);64 returntoken;65 } catch(JWTCreationException exception) {66 //Invalid Signing configuration / Couldn't convert Claims.

67 throwexception;68 }69 }70

71 public staticBoolean verify(String token) {72 try{73 Algorithm algorithm =Algorithm.HMAC256(SECRET);74 JWTVerifier verifier = JWT.require(algorithm).build(); //Reusable verifier instance

75 DecodedJWT jwt =verifier.verify(token);76

77 String decodeHeader =StringUtils.newStringUtf8(Base64.decodeBase64(jwt.getHeader()));78 String decodePayload =StringUtils.newStringUtf8(Base64.decodeBase64(jwt.getPayload()));79

80 String signature =jwt.getSignature();81 String name = jwt.getClaim("name").asString();82 String introduce = jwt.getClaim("introduce").asString();83

84 System.out.println("header:" +jwt.getHeader());85 System.out.println("payload:" +jwt.getPayload());86 System.out.println("signature:" +signature);87

88 System.out.println("headerString:" +decodeHeader);89 System.out.println("payloadString:" +decodePayload);90

91 System.out.println("name:" +name);92 System.out.println("introduce:" +introduce);93 return true;94 } catch(JWTVerificationException exception) {95 System.out.println("当前时间:" + newDate());96 System.out.println("验证token失败:" +exception.getMessage());97 return false;98 }99 }100

101 public static voidmain(String[] args) {102 String token =create();103 //try {104 //Thread.sleep(3000l);105 //} catch (InterruptedException e) {106 // //TODO Auto-generated catch block107 //e.printStackTrace();108 //}

109 Boolean result =verify(token);110 System.out.println(result);111 }112 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值