使用jwt生成token登录
导入jwt的依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
生成token和解析token的工具类(相关的属性值放到配置文件中)
public class JwtUtils {
private static String key;
private static String header; //主要用于获取前端放在request的header
private static String mapKey;
@Value("${在配置文件中}")
public void setKey(String key) {
this.key = key;
}
@Value("${在配置文件中}")
public static void setHeader(String header) {
JwtUtils.header = header;
}
@Value("${在配置文件中}")
public static void setMapKey(String mapKey) {
JwtUtils.mapKey = mapKey;
}
//生成token
public static String createToken(Object obj){
Map map=new HashMap(); //map用于存储放在token的数据
map.put(mapKey,obj);
JwtBuilder jwtBuilder=Jwts.builder().setClaims(map).setIssuedAt(new Date()).signWith(SignatureAlgorithm.HS512,key);
return jwtBuilder.compact();
}
//解析token
public static Long getToken(HttpServletRequest request){
Claims claims=Jwts.parser().setSigningKey(key).parseClaimsJws(request.getHeader(header)).getBody();
Object obj=claims.get(mapKey);
return userid;
}
}