jjwt demo

package jwt_demo;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.security.Key;
import java.text.SimpleDateFormat;
import java.util.Date;

public class App {
    public static void main(String[] args) throws InterruptedException {
        long now = System.currentTimeMillis();//当前时间
        long exp = now + 1000 * 60;//过期时间为1分钟

        // 这里是编码
        String secretString = "oP7WStjRND1iUQtALAAIUWEQSpjMyF7uXUda8Y2lDPQ=";
        SecretKey key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

        System.out.println(Encoders.BASE64.encode(key.getEncoded()));

        JwtBuilder builder = Jwts.builder().setId("888")
                .setIssuer("me")
                .setAudience("you")
                .setIssuedAt(new Date()) // for example, now
                .setSubject("小白")
                .setIssuedAt(new Date())
                .signWith(key)
                .setExpiration(new Date(exp))
                .claim("hello", "world")
                .setHeaderParam("kid", "myKeyId");
        String token = builder.compact();

        // 这里是解码
        SecretKey keyss = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));
        Jws<Claims> jws = Jwts.parserBuilder()
                .requireSubject("小白")
                .setSigningKey(keyss).build()
                .parseClaimsJws(token);

        JwsHeader header = jws.getHeader();
        Claims claim = jws.getBody();

        {
            System.out.println(jws.getSignature());
            System.out.println(header.getKeyId());
            System.out.println(claim.getId());
            System.out.println(claim.getSubject());
            System.out.println(claim.getIssuedAt());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy‐MM‐dd hh:mm:ss");
            System.out.println("签发时间:" + sdf.format(claim.getIssuedAt()));
            System.out.println("过期时 间:" + sdf.format(claim.getExpiration()));
            System.out.println("当前时间:" + sdf.format(new Date()));
        }

    }
}

你可能感兴趣的:(jjwt demo)