JWT使用

jjwt库github地址:https://github.com/jwtk/jjwt

1.pom.xml引入包

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-api</artifactId>
    <version>0.11.2</version>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-impl</artifactId>
    <version>0.11.2</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt-jackson</artifactId> <!-- or jjwt-gson if Gson is preferred -->
    <version>0.11.2</version>
    <scope>runtime</scope>
</dependency>
<!-- Uncomment this next dependency if you are using JDK 10 or earlier and you also want to use 
     RSASSA-PSS (PS256, PS384, PS512) algorithms.  JDK 11 or later does not require it for those algorithms:
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.60</version>
    <scope>runtime</scope>
</dependency>
-->

 

 2.测试用例

/**
 * @Author: ltx
 * @Date: 2020/9/16 10:07
 * @Description: jwt例子,具体的jwt文档看这里
 * https://github.com/jwtk/jjwt
 */
@Slf4j
public class JwtTest {
    //jwt签名密钥,一般从配置文件读取
    static final String SECRET = "58f85fcf-cdba-447c-8082-5ec61494c808";
    //签名key
    static final SecretKey key = Keys.hmacShaKeyFor(SECRET.getBytes());

    @Test
    public void jwtTest() {
        //可以存任何值到自包含里面
        HashMap<String, Object> mapValue = new HashMap<>(16);
        mapValue.put("id", "1019");
        mapValue.put("username", "admin_ltx");

        String jws = Jwts.builder()
                //数据体里面放数据(map)
                .setClaims(mapValue)
                .setId("8888")
                .setIssuer("user007")
                //头里面放数据(demo)
                .setHeaderParam("kid", "myKeyId")
                //设置签发时间
                .setIssuedAt(new Date())
                //不应该使用在此时间戳之后获得的JWT, 有效期7天, 过期会报ExpiredJwtException异常
                .setExpiration(DateUtil.offsetDay(new Date(), 7))
                //不应该使用在此时间戳之前获得的JWT, 相当于提前给你这个token,但到了这个时间之后才能使用
//                .setNotBefore(new Date())
                .setSubject("Joe")
                //设置签名秘钥, SignatureAlgorithm.HS256 这个可以不写,默认就是使用SHA-256加密算法
                .signWith(key, SignatureAlgorithm.HS256).compact();
        // 13:52:26.401 [main] INFO com.qmy.crmadmin.JwtTest - eyJraWQiOiJteUtleUlkIiwiYWxnIjoiSFMyNTYifQ.eyJpZCI6IjEwMTkiLCJ1c2VybmFtZSI6ImFkbWluX2x0eCIsImlhdCI6MTYwMDIzNTU0NSwiZXhwIjoxNjAwODQwMzQ1LCJzdWIiOiJKb2UifQ.RhcOXuPXs_IJv4SEckS_mItR4ZOi2cM2CroFAmq_J5Y
        log.info(jws);
        //解析校验
        try {
            Jws<Claims> parserJws = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(jws);
            // 13:52:26.457 [main] INFO com.qmy.crmadmin.JwtTest - header={kid=myKeyId, alg=HS256},body={id=1019, username=admin_ltx, iat=1600235545, exp=1600840345, sub=Joe},signature=RhcOXuPXs_IJv4SEckS_mItR4ZOi2cM2CroFAmq_J5Y
            log.info("{}", parserJws);
        } catch (MalformedJwtException e) {
            log.error("JWT签名格式不对!");
            log.error(e.getMessage(), e);
        } catch (SignatureException e) {
            log.error("JWT签名不匹配");
            log.error(e.getMessage(), e);
        } catch (ExpiredJwtException e) {
            log.error("JWT签名过期了");
            log.error(e.getMessage(), e);
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小小绿豆

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

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

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

打赏作者

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

抵扣说明:

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

余额充值