java生成tonken工具类

java生成tonken工具类

package com.cgnpc.imsqs.utils;



import cn.hutool.core.bean.BeanUtil;

import com.auth0.jwt.JWT;

import com.auth0.jwt.JWTVerifier;

import com.auth0.jwt.algorithms.Algorithm;

import com.auth0.jwt.exceptions.JWTCreationException;

import com.auth0.jwt.exceptions.JWTDecodeException;

import com.auth0.jwt.exceptions.JWTVerificationException;

import com.auth0.jwt.interfaces.DecodedJWT;

import com.cgnpc.cud.core.exception.BaseServiceException;

import com.cgnpc.framework.exception.BusinessException;

import com.cgnpc.imsqs.app.util.AppUser;

import lombok.extern.slf4j.Slf4j;

import org.springframework.util.StringUtils;

import org.springframework.web.context.request.RequestContextHolder;

import org.springframework.web.context.request.ServletRequestAttributes;



import javax.servlet.http.HttpServletRequest;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Map;



/**

 * 自定义token

 * @author 

 */

@Slf4j

public class TokenUtil {



    //token到期时间7天

    private static final long EXPIRE_TIME = 7 * 24 * 60 * 60 * 1000;



    //密钥盐

    private static final String TOKEN_SECRET = "l122adasw532df";



    /**

     * 创建一个token

     * @param map

     * @return

     */

    public static String sign(Map<String,Object> map) {

        String token = null;

        try {

            Date expireAt = new Date(System.currentTimeMillis() + EXPIRE_TIME);

            token = JWT.create()

                    .withIssuer("auth0")//发行人

                    .withClaim("userNo", map)   //存放数据

                    .withExpiresAt(expireAt)//过期时间

                    .sign(Algorithm.HMAC256(TOKEN_SECRET));

        } catch (IllegalArgumentException | JWTCreationException je) {

            log.error("令牌创建失败!{}",je);

        }

        return token;

    }





    /**

     * 对token进行验证

     *

     * @param token

     * @return

     */

    public static Boolean verify(String token) {

        try {

            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET))

                    .withIssuer("auth0").build();//创建token验证器

            DecodedJWT decodedJWT = jwtVerifier.verify(token);

            log.info("认证通过:");

            log.info("userId: {} 过期时间:{}", TokenUtil.getUser(token), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(decodedJWT.getExpiresAt()));

        } catch (IllegalArgumentException | JWTVerificationException e) {

            log.error("token 验证异常:{}", e);

            //抛出错误即为验证不通过

            return false;

        }

        return true;

    }



    /**

     * 获取用户信息

     */

//    public static Map<String,Object> getUserNo(String token) {

//        Map<String,Object> userNo = null;

//        try {

//            DecodedJWT jwt = JWT.decode(token);

//            userNo = jwt.getClaim("userNo").asMap();

//        } catch (JWTDecodeException e) {

//            log.error("获取用户信息异常:{}", e);

//        }

//        return userNo;

//    }



    /**

     * 获取用户信息

     */

    public static AppUser getUser(String token) {

        AppUser appUser;

        if(token == "" || token == null){

            return null;

        }

        try {

            DecodedJWT jwt = JWT.decode(token);

            Map<String,Object> userNo = jwt.getClaim("userNo").asMap();

            appUser = BeanUtil.fillBeanWithMap(userNo,new AppUser(),false);

        } catch (JWTDecodeException e) {

            log.error("获取用户信息异常:{}", e);

            throw new BusinessException("获取用户信息异常");

        }

        return appUser;

    }





    public static AppUser getCurrentUser(){

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        String sign = request.getAttribute("sign").toString();

        if(StringUtils.isEmpty(sign)){

            throw new BaseServiceException("获取app用户加密信息异常");

        }

        return getUser(sign);

    }



    public static String getToken(){

        String sign = "";

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        try{

            sign = request.getAttribute("sign").toString();

        }catch (Exception e){

            sign = "";

        }

        return sign;

    }







    public static void main(String[] args) {

//        String token = sign(4);

//        System.out.println("token:"+token);

//        Integer userNo = getUserNo(token);

//        System.out.println("getUserNo"+userNo);

//        Boolean verify = verify(token);

//        System.out.println("verify:"+verify);

//        String token = sign(4);

//        System.out.println("token:"+token);

//        String token1 = sign(4);

//        System.out.println("token:"+token1);

//        Boolean verify = verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTm8iOjQsImlzcyI6ImF1dGgwIiwiZXhwIjoxNjczNDg3ODE1fQ.dKz3psNRyNwsSjEQ3bcw909b9yDcvv4HpFuSrSynclk");

//        System.out.println("verify:"+verify);

//        Boolean verify1 = verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTm8iOjQsImlzcyI6ImF1dGgwIiwiZXhwIjoxNjczNDg3ODE2fQ.RUhiMmaVWKIEGBqbR8rTrEbE1O5wnqzFHuVGfLgppMg");

//        System.out.println("verify1:"+verify1);

//        Boolean verify2 = verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTm8iOjQsImlzcyI6ImF1dGgwIiwiZXhwIjoxNjczNDg3ODE2fQ.RUhiMmaVWKIEGBqbR8rTrEbE1O5wnqzFHuVGfLgppkk");

//        System.out.println("verify2:"+verify2);

        System.out.println(System.currentTimeMillis()/1000);

    }



}

      
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坏女人净画饼

原创辛苦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值