TokenService.java 2.92 KB
package com.huaheng.framework.token;



import com.huaheng.framework.redis.RedisCache;
import com.huaheng.pc.system.user.domain.User;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;


/**
 * token生成与解析
 * @author Enzo Cotter
 * @date 2020/6/11
 */
@Service
public class TokenService {

    @Resource
    private RedisCache redisCache;


    private static final Logger log = LoggerFactory.getLogger(TokenService.class);

    /**
     * 有效期7天
     */
    private static final int EXPIRE_TIME = 7;
    /**
     * 盐
     */
    public static final String SIGNINGKEY = "OldSuperMan";


    /**
     * 创建token
     * @param user 用户
     * @return
     */
    public String createToken(User user, String password){
        Claims claims = Jwts.claims();
        user.setPassword(password);
        claims.put("user", user);
        JwtBuilder builder = Jwts.builder().setClaims(claims)
                //签发时间
                .setIssuedAt(new Date())
                //签名算法以及密匙
                .signWith(SignatureAlgorithm.HS512,SIGNINGKEY);

//        if (redisCache.setCacheObject(token, user.toString(), EXPIRE_TIME, TimeUnit.DAYS) == null) {
//            throw new ServiceException("redis异常");
//        }
        if (EXPIRE_TIME >= 0) {
            LocalDateTime expDate = LocalDateTime.now();
            expDate = expDate.plusDays(EXPIRE_TIME);
            // 过期时间
            builder.setExpiration(Date.from(expDate.atZone(ZoneId.systemDefault()).toInstant()));
        }
        return builder.compact();
    }

    /**
     * 创建token
     * @param user 用户
     * @return
     */
    public String createTokenForMobile(User user){
        //签发时间
        Date iatTime = new Date();
        //expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.DATE, EXPIRE_TIME);

        Claims claims = Jwts.claims();
        claims.put("user", user);
        claims.setIssuedAt(iatTime);
        String token = Jwts.builder().setClaims(claims)
                .signWith(SignatureAlgorithm.HS512,SIGNINGKEY).compact();
        //Date expireTime = nowTime.getTime();
//        if (redisCache.setCacheObject(token, user.toString(), EXPIRE_TIME, TimeUnit.DAYS) == null) {
//            throw new ServiceException("redis异常");
//        }
        return token;
    }

    /**
     * 解析token
     * @param token
     */
    public void parseToken(String token){
        Jws<Claims> jws = Jwts.parser().setSigningKey(SIGNINGKEY).parseClaimsJws(token);
        Claims claims = jws.getBody();
        Map<String,String> header = jws.getHeader();
        System.out.println("parse" + header);
        log.warn("Token:"+ header);
    }
}