JwtUtil

package com.zhjt.zhdataexchange.utils;

import io.jsonwebtoken.*;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @program: bzwz
 * @description: Jwt验证工具类
 * @author: HXf
 * @create: 2019-01-16 10:43
 **/
@Component
@ConfigurationProperties("jwt.config")
public class JwtUtil {

    private String key;

    private Long ttl;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Long getTtl() {
        return ttl;
    }

    public void setTtl(Long ttl) {
        ttl = ttl*1000*60*60;
        this.ttl = ttl;
    }

    /**
     * @Description:  创建jwt
     * @Param: [id, subject, roles]
     * @return: java.lang.String
     * @Author: hxf
     * @Date: 11:12
     */
    public String createJWT(String id,String subject,String roles){
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(now).signWith(SignatureAlgorithm.HS256, key)
                .claim("roles", roles);
        if(ttl>0){
            builder.setExpiration(new Date(nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * @Description: 解析JWT
     * @Param: [jwtStr]
     * @return: io.jsonwebtoken.Claims
     * @Author: hxf
     * @Date: 11:51
     */
    public Claims parseJWT(String jwtStr){
        try{
            return Jwts.parser().setSigningKey(key).parseClaimsJws(jwtStr).getBody();
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("登陆过期");
            //return null;
        }
    }
}

你可能感兴趣的:(JwtUtil)