JWT工具类

<!-- token -->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
package com.example.mongodemo.util;


import com.example.mongodemo.code.JWTCode;

import io.jsonwebtoken.*;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.concurrent.TimeUnit;


public class JWTUtil
{
    private final static Logger logger = LoggerFactory.getLogger(JWTUtil.class);

    /*
     * 密文,用于加密解密Signature
     */
    private static final String JWT_SECRET = "fnarip*fudasfasfas5fa9sdf_jcewdiudsad56161bfof_1564d16";

    /**
     * 创建jwt
     *
     * @param id        用户的id
     * @param ttlMillis 过期的时间长度
     * @return token串
     * @throws Exception
     */
    public static String createJWT(String id, long ttlMillis) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();// 签发jwt的时间
        SecretKey key = generalKey();
        JwtBuilder builder = Jwts.builder().setIssuedAt(new Date())// 签发时间

                .claim("openId", id)// 用户id
                .signWith(signatureAlgorithm, key).setExpiration(new Date(nowMillis + ttlMillis));

//		System.out.println(nowMillis );
//		System.out.println( ttlMillis);
        return builder.compact();
    }

    /**
     * 生成加密秘钥
     *
     * @return 秘钥
     */
    private static SecretKey generalKey() {
        String stringKey =  JWT_SECRET;// 秘钥
        byte[] encodedKey = Base64.decodeBase64(stringKey);
        SecretKey key = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 验证token
     *
     * @param jwt token串
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws RuntimeException {
        SecretKey key = generalKey();
        Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(jwt).getBody();
        return claims;
    }

    /**
     * 验证token并返回信息
     * @param token
     * @return
     */
    public static JWTCode judgeToken(String token){
        try{
              parseJWT(token);
        }
        catch (ExpiredJwtException e) {

            logger.info("token过期!",e);
            return JWTCode.OVERDUE;
        } catch (Exception e) {

            logger.info("token无效!",e);
            return JWTCode.ERROR;
        }
        return JWTCode.SUCCESS;
    }


    public static String getOpenId(HttpServletRequest request){
        String token = request.getHeader("token");
        String openId = "";
        try {
            openId = parseJWT(token).get("openId").toString();
        }
        catch (Exception e){
            System.out.println("tokn解析openId失败");
            logger.error("tokn解析openId失败!",e);
            return null;
        }
        return openId;
    }


    public static void main(String[] args) {
        try {

            String token =  createJWT("asdfafas",TimeUnit.HOURS.toMillis(10));
            Cookie cookie = StringUtil.setCookie("mwentoken",token, (int)TimeUnit.HOURS.toMillis(10)) ;
            String value =StringUtil.getCookie("mwentoken",new Cookie[]{cookie});
            System.out.println(value);
            System.out.println(token);
            System.out.println(  parseJWT(value).get("openId").toString());
//			 System.out.println(JWTUtils.parseJWT("eyJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NDQwODQ2NDUsInVOYW1lIjoiaGFuaGFvIiwidUlkIjoiOSIsImV4cCI6MTU0NTg4NDY0NX0.NrqMOWG0AadZUX1ZHkQukZakRz-SgOLqrKjytBEb33c").get("uName").toString());
        } catch (ExpiredJwtException e) {
            System.out.println("token过期");
        } catch (Exception e) {
            System.out.println("token无效!!!");
            e.printStackTrace();
        }
    }

}
package com.example.mongodemo.util;

import com.example.mongodemo.dto.ResultDTO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

/**
 * @Author lyr
 * @create 2020/3/26 17:10
 *
 * https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
 *
 * 增加微信登录功能
 *
 */
public  class StringUtil {

     //TODO:记得改过来
    private static String TOKEN = "config";


    public static String md5(String... args) throws NoSuchAlgorithmException {
        MessageDigest messageDigest =  MessageDigest.getInstance("MD5");
        String res = String.join("", args);
        return new String(messageDigest.digest(res.getBytes()));
    }

    /**
     * 验证签名
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */

    public static boolean checkSignature(String signature, String timestamp,
                                         String nonce) {
        String[] arr = new String[] { TOKEN, timestamp, nonce };
        // 将token、timestamp、nonce三个参数进行字典序排序
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (String s : arr) {
            content.append(s);
        }
        MessageDigest md = null;
        String tmpStr = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }


        // 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
        return tmpStr != null && tmpStr.equals(signature.toUpperCase());
    }


    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        StringBuilder strDigest = new StringBuilder();
        for (int i = 0; i < byteArray.length; i++) {
            strDigest.append(byteToHexStr(byteArray[i]));
        }
        return strDigest.toString();
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A',
                'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];

        return new String(tempArr);
    }

    public static Cookie setCookie(String name, String value, int time) throws UnsupportedEncodingException {
        String v = URLEncoder.encode(value, "utf-8");
        Cookie cookie = new Cookie(name,v);
        cookie.setMaxAge((int) time);
        cookie.setPath("/");
        return cookie;

    }
    public static String getCookie(String key,Cookie[] cookie) throws UnsupportedEncodingException {
        for (int i=0;i<cookie.length;++i) {
            if(cookie[i].getName().equals(key)) {
                return URLDecoder.decode(cookie[i].getValue(),"utf-8");
            }
        }
        return "NULL";



    }


    public static void renderJson(HttpServletResponse response, ResultDTO dto) {
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.print(dto.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            assert out != null;
            out.close();
        }

    }
}

package com.example.mongodemo.code;

/**
 * @Author lyr
 * @create 2020/3/28 12:26
 */
public enum JWTCode {
    SUCCESS,ERROR,OVERDUE;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值