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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.google.gson.JsonObject;
import com.huaheng.common.exception.service.ServiceException;
import com.huaheng.framework.redis.RedisCache;
import com.huaheng.pc.system.user.domain.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jdk.nashorn.internal.parser.JSONParser;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

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

    @Resource
    private RedisCache redisCache;

    /**
     * 有效期7天
     */
    private static final int EXPIRE_TIME = 7;

    /**
     * 盐
     */
    private static final String signingKey = "secret";

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

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

    /**
     * 创建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);
        Date expireTime = nowTime.getTime();

        Claims claims = Jwts.claims();
        claims.put("user", user);
        claims.setIssuedAt(iatTime);
        String token = Jwts.builder().setClaims(claims)
                .signWith(SignatureAlgorithm.HS512,signingKey).compact();
//        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");
    }
}