使用JWT

 1、导入相关jar包,资源地址:https://download.csdn.net/download/china574512989/10730677

使用JWT_第1张图片

2、生成Token

public   String createJWT(String id, String issuer, String subject, long ttlMillis) {
		 
		SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
		 
		long nowMillis = System.currentTimeMillis();
		Date now = new Date(nowMillis);
		 
		byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(ViewConstant.ACS_JWT_KEY);
		Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
		 
		JwtBuilder builder = Jwts.builder().setId(id)
		                                .setIssuedAt(now)
		                                .setSubject(subject)
		                                .setIssuer(issuer)
		                                .signWith(signatureAlgorithm, signingKey);
		 
		if (ttlMillis >= 0) {
		    long expMillis = nowMillis + ttlMillis;
		    Date exp = new Date(expMillis);
		    builder.setExpiration(exp);
		}
		 
		return builder.compact();
		}

 解析:

SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

指定算法为HS256,还有许多种,可以查API

byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(ViewConstant.ACS_JWT_KEY);
Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

ViewConstant.ACS_JWT_KEY为自定义的秘钥。

3、解密

public Claims getClaims(String jwt){
		return Jwts.parser()      
				   .setSigningKey(DatatypeConverter.parseBase64Binary(ViewConstant.ACS_JWT_KEY))
				   .parseClaimsJws(jwt).getBody();
	}

4、获取元素

Claims claims = acsService.getClaims(acsToken);
String a=claims.getId();
String b=claims.getSubject();
String c=claims.getIssuer();

 

你可能感兴趣的:(笔记)