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

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

导入io.jsonwebtoken依赖:


  io.jsonwebtoken
  jjwt
  0.9.1

jwt的简单使用:

生成token

@Test
public void testIoJsonWebToken() {
  String key = "myKey";
  HashMap 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 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 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();
    }
}

你可能感兴趣的:(jwt,java,git,markdown,密码学)