package com.care.util; import cn.hutool.json.JSONUtil; import com.care.common.vo.UserLogindConvertVO; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import javax.annotation.Resource; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.security.Key; import java.util.Date; /** * Created by y on 2017/11/16. * @author y */ @Component @PropertySource(value = "classpath:common.properties", ignoreResourceNotFound = true) public class JwtUtils { private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class); @Resource private Environment env; /** * 由字符串生成加密key * @return */ public SecretKey generalKey() { String stringKey = env.getProperty("auth.jwt.id") + env.getProperty("auth.jwt.secret"); byte[] encodedKey = Base64.decodeBase64(stringKey); SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES"); return key; } public String generalToken(UserLogindConvertVO userLogindConvertDTO) { String compactJws = null; try { long nowMillis = System.currentTimeMillis(); Date now = new Date(nowMillis); Key key = generalKey(); compactJws = Jwts.builder() .setSubject(JSONUtil.toJsonStr(userLogindConvertDTO)) .setIssuedAt(now) .signWith(SignatureAlgorithm.HS512, key) .setExpiration(new Date(nowMillis + env.getProperty("auth.jwt.ttl.ms", Long.class))) .compact(); } catch (Exception e) { logger.error("生成TOKEN出现异常.", e); } return compactJws; } /** * 解密jwt * @param jwt * @return * @throws Exception */ public Claims tokenParse(String jwt) { SecretKey key = generalKey(); Claims claims = null; try { claims = Jwts.parser() .setSigningKey(key) .parseClaimsJws(jwt).getBody(); } catch (io.jsonwebtoken.ExpiredJwtException e) { System.out.println("当前TOKEN已过期, 请重新登录."); } catch (Exception e) { System.out.println("校验TOKEN出现异常, 请重新登录."); } return claims; } }