1.pom导入相关依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
2.配置你想暴露的信息实体(不要暴露敏感信息)
@Data
@AllArgsConstructor
@NoArgsConstructor
public class JwtInfo {
private String id;
private String nickname;
private String avatar;
}
3.编写JWT工具类
/**
* 工具类
* JWT工具
*/
@Slf4j
public class JwtUtil {
public static final String APP_SECRET="usdiausASDHsahaASKDJ";
//生成key(加密)
private static Key getKeyInstance(){
SignatureAlgorithm signatureAlgorithm=SignatureAlgorithm.HS256;//签名算法
byte[] bytes= DatatypeConverter.parseBase64Binary(APP_SECRET);
return new SecretKeySpec(bytes,signatureAlgorithm.getJcaName());
}
//获取jwt TOKEN
public static String getToken(JwtInfo jwtInfo,int expire){
String JwtToken= Jwts.builder()
.setHeaderParam("typ","JWT")
.setHeaderParam("alg","HS256")
.setSubject("guli-user")//设置主题
.setIssuedAt(new Date())//颁发时间
.setExpiration(DateTime.now().plusSeconds(expire).toDate())//过期时间
.claim("id",jwtInfo.getId())//id
.claim("nickname",jwtInfo.getNickname())//name
.claim("avatar",jwtInfo.getAvatar())//头像
.signWith(SignatureAlgorithm.HS256,getKeyInstance())//签名
.compact();
return JwtToken;
}
//判断token是否存在或者有效
public static boolean checkJwtToken(HttpServletRequest request){
try {
String jwtToken=request.getHeader("token");
if (StringUtils.isEmpty(jwtToken)){
return false;
}
Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
}
catch (Exception e){
return false;
}
return true;
}
//解析 根据token解析id
public static JwtInfo getMemberInfoByToken(HttpServletRequest request){
String jwtToken=request.getHeader("token");
if (StringUtils.isEmpty(jwtToken)) return null;
try {
Jws<Claims> claimsJws = Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwtToken);
Claims claims=claimsJws.getBody();
JwtInfo jwtInfo=new JwtInfo(claims.get("id").toString(),claims.get("nickname").toString(),claims.get("avatar").toString());
return jwtInfo;
}
catch (Exception e){
log.info("非法token入侵");
return null;
}
}
}
4.使用jwt工具就能校验前端回写的token