jwt生成token的算法java类

主要的代码:

主要可以实现生成token,然后这个可以保存在reddish里面这样每一次用户操作鉴权就可以正常的进行了


public class JwtToken {
    /**
     * jwt密钥
     */
    private static String jwtSecret = "6077df7fc3a34e26a61c034d5ec8245d";

    /**
     * token有效期为3天半,白天登录时夜晚过期
     */
    private static long expTime = 35 * 100 * 24 * 60 * 60L;


    public static String buildToken(String appKey){
        if(null==appKey){
            return null;
        }
        SecretKey key = new SecretKeySpec(jwtSecret.getBytes(),0, jwtSecret.getBytes().length, "AES");
        // 设置算法为HS256
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        Date now = new Date(System.currentTimeMillis());
        Date exp = new Date(System.currentTimeMillis() + expTime);
        JwtBuilder builder = Jwts.builder().setHeaderParam("typ", "JWT").setHeaderParam("alg", "HS256").setIssuedAt(now)
                .claim("appKey", appKey).setExpiration(exp).signWith(signatureAlgorithm, key);
        return builder.compact();
    }


    public static boolean isEffectiveToken(String token)  {
        boolean isEffectiveToken = true;
        try {
            Claims claims = Jwts.parser().setSigningKey(jwtSecret.getBytes()).parseClaimsJws(token).getBody();
            /*isEffectiveToken = claims.getExpiration().getTime() - System.currentTimeMillis() > 0;*/
        }catch (ExpiredJwtException e){
            e.printStackTrace();
            isEffectiveToken = false;
        }
        return isEffectiveToken;
    }

    public static String getUserAccount(String token){
        if(null == token){
            return null;
        }
        Claims claims = Jwts.parser().setSigningKey(jwtSecret.getBytes()).parseClaimsJws(token).getBody();
        return claims.get("appKey").toString();
    }


}

依赖的jar

  <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
        </dependency>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

道阻且长-行则将至-行而不辍-未来可期

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值