使用 io.jsonwebtoken 实现token的生成与解码

通过 jsonwebtoken 能够方便的生成token和进行token相关解码,参考文档:https://github.com/jwtk/jjwt#base64 ,详细的操作流程如下所示

导入io.jsonwebtoken依赖:

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

jwt的简单使用:

生成token

@Test
public void testIoJsonWebToken() {
  String key = "myKey";
  HashMap<String, Object> map = new HashMap<>();
  map.put("name", "get");
  String jwt = Jwts.builder()
    .signWith(SignatureAlgorithm.HS256, key)
    .setClaims(map)
    .compact();
  System.out.println(jwt); // eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiZ2V0In0.RiKlMMNgv3XRDcZtxgukAEpOHv_Q9pQQjDPPuPa-Dw0
}

解析token,对生成的token进行解密操作

@Test
public void parseJsonWebToken() {
  String key = "myKey";
  Jws<Claims> jws = Jwts.parser()
    .setSigningKey(key)
 .parseClaimsJws("eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiZ2V0In0.RiKlMMNgv3XRDcZtxgukAEpOHv_Q9pQQjDPPuPa-Dw0");
  System.out.println(jws.getBody());
  System.out.println(jws.getBody().get("name"));
}

封装jwt工具类

实体类:

public class User implements Serializable {
    private String name;
    private Integer age;
    private String password;

    public User(String name, Integer age, String password) {
        this.name = name;
        this.age = age;
        this.password = password;
    }
    // get set 方法
}

工具类:

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class JwtHelper {
    private static final String key = "keyxxx";

    public static String createJWT(Object obj) {
        Map<String, Object> map = new HashMap<>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                map.put(field.getName(), field.get(obj));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, key)
                .setClaims(map)
                .compact();
    }

    public static Claims parseJWT(String token) {
        return Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(token)
                .getBody();
    }
}
posted @ 2021-12-31 16:58  GetcharZp  阅读(1399)  评论(0编辑  收藏  举报