在web应用方面,主要的会话保持技术有三种,分别是Cookie,Session和Jwt技术,cookie将数据明文保存在客户端,有严重的安全问题,session基于cookie实现,将sessionId保存在cookie中,将真实数据保存在服务端,成功的解决了安全问题,但是session是基于cookie实现的,所有他还存在一些问题,比如现在企业服务器大多以集群的形式存在,web请求被负载均衡服务器随机指定集群中的一台服务器处理,可能在该台服务器中不存在sessionId对应的数据。cookie和session不支持移动端,也不能跨域。
jwt(Json Web Token)令牌技术正是为解决上述问题而出现的,它由客户端保存,由签名算法信息,自定义信息和密钥三部分组成。
接下来使用java实现jwt令牌的生成和解析
首先导入相关依赖
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.11.5</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.11.2</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.11.2</version>
</dependency>
然后实现一个Jwt类
public class JwtUtil {
private static final SignatureAlgorithm signatureAlgorithm=SignatureAlgorithm.HS256;//指定加密算法
private static final Long expire= (long) (60*60*1000);//设置有效时间
private static final String secret="mynameiszoffyandhisnameisminghuang";//设置密钥
public String GenerateJwt(Map<String,Object> claims){
Key signatureKey=new SecretKeySpec(secret.getBytes(),signatureAlgorithm.getJcaName());
return Jwts.builder()
.signWith(signatureKey,SignatureAlgorithm.HS256)//设置签名方式
.addClaims(claims)//设置自定义消息
.setExpiration(new Date(System.currentTimeMillis()+expire))//设置过期时间
.compact();
}
public Map<?,?> ParseJwt(String jwt){
Key signatureKey=new SecretKeySpec(secret.getBytes(),signatureAlgorithm.getJcaName());
Object body=Jwts.parserBuilder()
.setSigningKey(signatureKey)
.build()
.parse(jwt)
.getBody();
return (Map<?,?>)body;
}
}
测试一下
public static void main(String[] args){
JwtUtil jwtUtil=new JwtUtil();
Map<String,Object> map=new HashMap<>();
map.put("name","zoffy");
map.put("hello","chen");
String jwt=jwtUtil.GenerateJwt(map);
System.out.println(jwt);
System.out.println(jwtUtil.ParseJwt(jwt));
}
成功