使用jwt记录

pom依赖

        <!--        jwt依赖-->
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

 

代码:

package com.example.demo;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.Base64Codec;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@SpringBootTest
class JwtDemoApplicationTests {
    // 盐值
    public static final String KEY = "xiehui";


    // 生成jwt
    @Test
    public void contextLoads() {
        String token = Jwts.builder()
                // 设置id {"jti":"666"}
                .setId("666")
                // 签发用户 {"sub":"admin"}
                .setSubject("admin")
                // 签发时间 {"iat":"xxxx"}
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, KEY).compact();
        System.out.println(token);
        String[] split = token.split("\\.");
        // 头部信息
        System.out.println(Base64Codec.BASE64.decodeToString(split[0]));
        // 负载
        System.out.println(Base64Codec.BASE64.decodeToString(split[1]));
        // 签名
        System.out.println(Base64Codec.BASE64.decodeToString(split[2]));
    }

    // 解析jwt
    @Test
    public void parseJwt() {
        String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NjYiLCJzdWIiOiJhZG1pbiIsImlhdCI6MTYyMTY3MzY3NX0.XDx7j5wf8CQQLetnS624izT0S69HFOUaivGGDlzgXkc";
        Claims claims = Jwts.parser()
                .setSigningKey(KEY)
                .parseClaimsJws(jwt)
                .getBody();
        System.out.println("jti:" + claims.getId());
        System.out.println("sub:" + claims.getSubject());
        System.out.println("iat:" + claims.getIssuedAt());


    }


    // 创建jwt带过期时间
    @Test
    public void createJwtByExpireTime() {
        long now = System.currentTimeMillis();
        long expiretime = now + 60 * 1000; // 一分钟过期

        String token = Jwts.builder()
                // 设置id {"jti":"666"}
                .setId("666")
                // 签发用户 {"sub":"admin"}
                .setSubject("admin")
                // 签发时间 {"iat":"xxxx"}
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, KEY)
                // 设置过期时间
                .setExpiration(new Date(expiretime))
                .compact();

        System.out.println(token);
        String[] split = token.split("\\.");
        // 头部信息
        System.out.println(Base64Codec.BASE64.decodeToString(split[0]));
        // 负载
        System.out.println(Base64Codec.BASE64.decodeToString(split[1]));
        // 签名
        System.out.println(Base64Codec.BASE64.decodeToString(split[2]));
    }

    // 解析带过期时间的jwt
    @Test
    public void parseHasExpireTimeJwt() {
        String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NjYiLCJzdWIiOiJhZG1pbiIsImlhdCI6MTYyMTY3NDU4OCwiZXhwIjoxNjIxNjc0NjQ4fQ.qqGvg4vnsZOw7stF9HB_bDLF83y4U2NyVmkcxAMJ29c";
        Claims claims = Jwts.parser()
                .setSigningKey(KEY)
                .parseClaimsJws(jwt)
                .getBody();
        System.out.println("jti:" + claims.getId());
        System.out.println("sub:" + claims.getSubject());
        System.out.println("iat:" + claims.getIssuedAt());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("签发时间:" + simpleDateFormat.format(claims.getIssuedAt()));
        System.out.println("当前时间:" + simpleDateFormat.format(new Date()));
        // 如果超过过期时间抛出ExpiredJwtException异常
        System.out.println("过期时间:" + simpleDateFormat.format(claims.getExpiration()));
    }


    //创建自定义声明内容的jwt
    @Test
    public void createHasCustomJwt() {
        // 自定义内容
        Map<String, Object> myClaims = new HashMap<>();
        myClaims.put("name", "谢辉");
        myClaims.put("age", 18);

        String token = Jwts.builder()
                // 设置id {"jti":"666"}
                .setId("666")
                // 签发用户 {"sub":"admin"}
                .setSubject("admin")
                // 签发时间 {"iat":"xxxx"}
                .setIssuedAt(new Date())
                .signWith(SignatureAlgorithm.HS256, KEY)
                // 通过map添加自定义内容
                .addClaims(myClaims)
                // 一条一条添加内容
                .claim("sex", "男")
                .compact();
        System.out.println(token);
        String[] split = token.split("\\.");
        // 头部信息
        System.out.println(Base64Codec.BASE64.decodeToString(split[0]));
        // 负载
        System.out.println(Base64Codec.BASE64.decodeToString(split[1]));
        // 签名
        System.out.println(Base64Codec.BASE64.decodeToString(split[2]));

    }

    // 解析自定义声明的jwt
    @Test
    public void parseHasCustomJwt() {
        String jwt = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI2NjYiLCJzdWIiOiJhZG1pbiIsImlhdCI6MTYyMTY3NTI2MSwibmFtZSI6Iuiwoui-iSIsImFnZSI6MTgsInNleCI6IueUtyJ9.eRmw16lZEZLXQUK86krLgUY4sbV5wbUJWdZ9OOiwNKY";
        Claims claims = Jwts.parser()
                .setSigningKey(KEY)
                .parseClaimsJws(jwt)
                .getBody();
        System.out.println("jti:" + claims.getId());
        System.out.println("sub:" + claims.getSubject());
        System.out.println("iat:" + claims.getIssuedAt());
        //获取自定义的内容
        System.out.println("name:" + claims.get("name"));
        System.out.println("age:" + claims.get("age"));
        System.out.println("sex:" + claims.get("sex"));
        // 过期时间
        // 过期时间:null,显示null表示永久有效
        System.out.println("过期时间:" + claims.getExpiration());

    }

}

地址:https://gitee.com/xieh-gitee/jwt-demo

 

posted @ 2021-05-22 17:29  图图小淘气_real  阅读(93)  评论(0编辑  收藏  举报