JWT初学-简单了解一下
demo代码git地址
jwt的maven依赖
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.0</version> </dependency>
json和实体类互转的依赖
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency>
首先生成加密的秘钥
public SecretKey generalKey(){ SecretKey secretKey = new SecretKeySpec(secret.getBytes(),SignatureAlgorithm.HS256.getJcaName()); return secretKey; }
创建jwt(加密算法+过期时间+实体内容+秘钥)
public String createJWT(String id,String subject){ //加密算法 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //设置时间 Calendar calendar = Calendar.getInstance(); Date date = calendar.getTime(); //过期时间 calendar.setTimeInMillis(date.getTime()+millis); Date expirationDate = calendar.getTime(); SecretKey secretKey = generalKey(); JwtBuilder builder = Jwts.builder() .setId(id) .setIssuedAt(date) .setSubject(subject) .signWith(signatureAlgorithm,secretKey) .setExpiration(expirationDate); return builder.compact(); }
解码jwt
public String parseJWT(String jwt){ SecretKey secretKey = generalKey(); return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody().getSubject(); }
获取过期时间
public Date expirateTime(String jwt){ SecretKey secretKey = generalKey(); return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody().getExpiration(); }
我们在操作jwt时,传入参数和返回的参数都是json字符串
public class Json { /** * 将对象转化成json字符串 * @param object * @return */ public String objetcToJson(Object object){ Gson gson = new Gson(); return gson.toJson(object); } public Object jsonToObject(String json,Class beanClass){ Gson gson = new Gson(); return gson.fromJson(json,beanClass); }}
实体类对象
public class UserPo { private String id; private String name; private int age; private boolean isMan; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public boolean isMan() { return isMan; } public void setMan(boolean man) { isMan = man; }}