JWT 创建和解析

1、创建、解析demo
public class JwtTest {
public static void createJwt(){
long l = System.currentTimeMillis();
long exp = l+1000*60;//过期时间1分钟
JwtBuilder jwtBuilder = Jwts.builder().setId(“1”)
.setSubject(“张三”)
.setIssuedAt(new Date())
.setExpiration(new Date(exp))
.signWith(SignatureAlgorithm.HS256, “itcast”)
.claim(“roles”,“admin”)
.claim(“logo”,“logo.png”);
System.out.println(jwtBuilder.compact());
}
public static void parseJwt(){
String token = “eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxIiwic3ViIjoi5byg5LiJIiwiaWF0IjoxNTkxNjg1NzI0LCJleHAiOjE1OTE2ODU3ODQsInJvbGVzIjoiYWRtaW4iLCJsb2dvIjoibG9nby5wbmcifQ.r5LnHcEhLMr39HewNDzfDkVA0z9GjtAnggtKFT733BI”;
Claims itcast = Jwts.parser().setSigningKey(“itcast”).parseClaimsJws(token).getBody();
System.out.println(itcast.getId());
System.out.println(itcast.getSubject());
System.out.println(itcast.getIssuedAt());
System.out.println(itcast.get(“roles”));
System.out.println(itcast.get(“logo”));
System.out.println(itcast.get(“logo11”));

    System.out.println("kk");
}

public static void main(String[] args) {
    //createJwt();
    parseJwt();
}

}

2封装工具类
@Data
@ConfigurationProperties(“jwt.config”)
public class JwtUtils {
//签名私钥
private String key;
//签名的失效时间
private Long ttl;
//设置token
public static void main(String[] args) {
JwtBuilder jwtBuilder = Jwts.builder().setId(“1234”).setSubject(“闪到”).setIssuedAt(new Date()).signWith(SignatureAlgorithm.HS256, “itcast”);
String compact = jwtBuilder.compact();
System.out.println(compact);

}
/**
 *  id 用户id
 *  subjecd用户名字
 * @return
 */
public String createJwt(String id, String name, Map map){
    long now = System.currentTimeMillis();
    long exp = now+ttl;
    JwtBuilder jwtBuilder = Jwts.builder().setId(id).
            setSubject(name).
            setIssuedAt(new Date()).
            setExpiration(new Date(exp)).
            signWith(SignatureAlgorithm.HS256, key);
    for (Map.Entry entry : map.entrySet()) {
        jwtBuilder.claim(entry.getKey(),entry.getValue());
    }
    String compact = jwtBuilder.compact();
    return compact;


}

//解析token获取
public Claims parseJWT(String token){
    Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
    return claims;
}

}
在application.properties中配置
jwt.config.key=saas-ihrm
jwt.config.ttl=360000

你可能感兴趣的:(php,java)