import cn.hutool.core.codec.Base64;
    import com.minglu.venus.common.constants.CommonConstant;
    import io.jsonwebtoken.Claims;
    import io.jsonwebtoken.JwtBuilder;
    import io.jsonwebtoken.Jwts;
    import io.jsonwebtoken.SignatureAlgorithm;

    import javax.crypto.spec.SecretKeySpec;
    import java.security.Key;
    import java.util.Calendar;
    import java.util.Date;

    public class TokenBuilder {

    1. private static Date getExpire(){<br /> Calendar calendar = Calendar._getInstance_();<br /> calendar.setTime(new Date());<br /> calendar.add(Calendar._HOUR_OF_DAY_,2);<br /> return calendar.getTime();<br /> }
    2. _/**_<br />_ * 生成jwt_<br />_ * _**_@param _**_appKey_<br />_ * _**_@param _**_appSecret_<br />_ * _**_@param _**_companyId_<br />_ * _**_@return_**<br />**_ _**_*/_<br />_ _public static String getToken(String appKey,String appSecret,Integer companyId,String companyName){<br /> _/**签名算法*/_<br />_ _SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm._HS256_;<br /> _/**密钥*/_<br />_ _byte[] keySecretBytes = Base64._decode_(CommonConstant._SECRET_);<br /> Key keys = new SecretKeySpec(keySecretBytes,signatureAlgorithm.getJcaName());<br /> JwtBuilder builder = Jwts._builder_()<br /> .claim(CommonConstant._COMPANY_ID_,String._valueOf_(companyId))<br /> .claim(CommonConstant._COMPANY_NAME_,companyName)<br /> .claim(CommonConstant._APP_KEY_,appKey)<br /> .claim(CommonConstant._APP_SECRET_,appSecret)<br /> .setIssuedAt(new Date())<br /> .setExpiration(_getExpire_())<br /> .signWith(signatureAlgorithm,keys);<br /> return builder.compact();<br /> }
    3. _/**_<br />_ * 解析jwt获取信息_<br />_ * _**_@param _**_token_<br />_ * _**_@return_**<br />**_ _**_*/_<br />_ _public static TokenCompanyInfo parseToken(String token){<br /> Claims claims = Jwts._parser_()<br /> .setSigningKey(Base64._decode_(CommonConstant._SECRET_))<br /> .parseClaimsJws(token).getBody();<br /> TokenCompanyInfo info = new TokenCompanyInfo()<br /> .setCompanyName((String) claims.get(CommonConstant._COMPANY_NAME_))<br /> .setCompanyId(Long._valueOf_((String)claims.get(CommonConstant._COMPANY_ID_)));<br /> return info;<br /> }
    4. _/**_<br />_ * 获取公司id_<br />_ * _**_@param _**_token_<br />_ * _**_@return_**<br />**_ _**_*/_<br />_ _public static Long getCompanyId(String token){<br /> return _parseToken_(token).getCompanyId();<br /> }
    5. _/**_<br />_ * 获取公司名称_<br />_ * _**_@param _**_token_<br />_ * _**_@return_**<br />**_ _**_*/_<br />_ _public static String getCompanyName(String token){<br /> return _parseToken_(token).getCompanyName();<br /> }