Java实现Token的生成与验证

二、基于JWT的token认证实现
JWT:JSON Web Token,其实token就是一段字符串,由三部分组成:Header,Payload,Signature
1、引入依赖

<dependency>
      <groupId>com.auth0</groupId>
      <artifactId>java-jwt</artifactId>
      <version>3.8.2</version>
</dependency>

2、设置密钥和生存时间

    //设置过期时间
    private static final long EXPIRE_TIME = 240 * 60 * 1000;
    //token秘钥
    private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618";

3、实现签名方法

public static String sign(String username, String permission) {
        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username,password信息,生成签名
            return JWT.create()
                    .withHeader(header)
                    .withClaim("loginName", username)
                    .withClaim("permission", permission)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

4、验证token

public static boolean verify(String token){
        /**
         * @desc   验证token,通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
            }
        }
        public static String parseJWT(String token){
            /**
             * @desc   解密token,返回一个map
             * @params [token]需要校验的串
             **/
            DecodedJWT decodeToken = JWT.decode(token);
            return decodeToken.getClaim("loginName").asString();
    }
        public static boolean isJwtExpired(String token){
            /**
             * @desc 判断token是否过期
             * @author lj
             */
        try {
            DecodedJWT decodeToken = JWT.decode(token);
            return decodeToken.getExpiresAt().before(new Date());
        } catch(Exception e){
            return true;
            }
        }
    }

5、token解码

public static String parseJWT(String token){
            /**
             * @desc   解密token,返回一个map
             * @params [token]需要校验的串
             **/
            DecodedJWT decodeToken = JWT.decode(token);
            return decodeToken.getClaim("loginName").asString();
    }

6、判断token是否过期

public static boolean isJwtExpired(String token){
            /**
             * @desc 判断token是否过期
             * @author lj
             */
        try {
            DecodedJWT decodeToken = JWT.decode(token);
            return decodeToken.getExpiresAt().before(new Date());
        } catch(Exception e){
            return true;
            }
        }
    }

7、测试

public static void main(String[] args) {
       String username ="zhangsan";
        String password = "123";
        String token = token(username,password);
        System.out.println(token);
        boolean b = verify(token);
        System.out.println(b);
    }

三、完整的Token工具类代码

public class JwtUtil {
    //设置过期时间
    private static final long EXPIRE_TIME = 240 * 60 * 1000;
    //token秘钥
    private static final String TOKEN_SECRET = "f26e587c28064d0e855e72c0a6a0e618";

    public static String sign(String username, String permission) {
        String token = "";
        try {
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username,password信息,生成签名
            return JWT.create()
                    .withHeader(header)
                    .withClaim("loginName", username)
                    .withClaim("permission", permission)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
    public static boolean verify(String token){
        /**
         * @desc   验证token,通过返回true
         * @params [token]需要校验的串
         **/
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
            }
        }
        public static String parseJWT(String token){
            /**
             * @desc   解密token,返回一个map
             * @params [token]需要校验的串
             **/
            DecodedJWT decodeToken = JWT.decode(token);
            return decodeToken.getClaim("loginName").asString();
    }
        public static boolean isJwtExpired(String token){
            /**
             * @desc 判断token是否过期
             * @author lj
             */
        try {
            DecodedJWT decodeToken = JWT.decode(token);
            return decodeToken.getExpiresAt().before(new Date());
        } catch(Exception e){
            return true;
            }
        }
    }

  • 4
    点赞
  • 61
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值