import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Service;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;
import java.util.UUID;

/**
 * Create by liping on 2018/9/25
 */
@Service
public class JWTService {
    private static final String encodekeys = "liping";

    private static SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS512;
    private static Key key;

//    @Value("${com.idoipo.jwt.encodedKey}")
//    private String encodedKey;

    /**
     * 初始化操作 @PostConstruct初始化完成后执行
     */
//    @PostConstruct
//    public void init() {
//        signatureAlgorithm = SignatureAlgorithm.HS512;
//        key = deserializeKey(encodedKey);
//    }

    /**
     * 生成加密解密key
     * @return
     */
    public static Key deserializeKey() {
        byte[] decodedKey = Base64.getDecoder().decode(encodekeys);

        Key key = new SecretKeySpec(decodedKey, JWTService.signatureAlgorithm.getJcaName());
        return key;
    }

    /**
     * 创建token 参数应该为自定义模型去传,用来设置token所携带字段
     * @return
     */
    public static String createToken(){
        key = deserializeKey();
        String token = Jwts.builder()
                .setSubject(UUID.randomUUID().toString())
                .claim("userName", "liping")
                .setIssuer("lp")
                .setAudience("xixi")
                .signWith(signatureAlgorithm, key).compact();
        return token;
    }

    public static String parseToken(String token){
        key = deserializeKey();
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
        return  claims.get("userName").toString();
    }

    public static void main(String[] args) {
        String token  = JWTService.createToken();
        System.out.println(token);
        String userName = JWTService.parseToken(token);
        System.out.println(userName);
    }
    


}

 

posted on 2018-09-25 20:38  不负前行  阅读(4056)  评论(0编辑  收藏  举报