生成 jwt 串的方法, Spring and Java

后续读取的文章 read jwt 的源代码,Spring Java-CSDN博客

通过 JSON Web Tokens - jwt.io

能看到 jwt 的解析

后续将自己生成的 jwt  拷贝到这里;就能看到 jwt 的解析结果。是否和自己定义的相同。

先见代码,为敬:

    public void testJWT() {

        Date expiration = new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24);
        Date notBefore = new Date(System.currentTimeMillis());
        String jws = Jwts.builder()

                .issuer("Baijing")
                .subject("Happy Birthday")
                .audience().add("wucaimu").and()
                .expiration(expiration) //a java.util.Date
                .notBefore(notBefore) //a java.util.Date
                .issuedAt(new Date()) // for example, now
                .id(UUID.randomUUID().toString()) //just an example id
                .compact();
        


        System.out.println(jws);

}

这里的解释,见官方文档 GitHub - jwtk/jjwt: Java JWT: JSON Web Token for Java and Android

极简的方式生成 jwt 字串

    @Test
    public void testJWT() {
        

        SecretKey key = Jwts.SIG.HS256.key().build();

        String jws = Jwts.builder().subject("BaiJing").signWith(key).compact();

        System.out.println(jws);

}

代码均已完成测试;有效。

完备的代码

       @Test
        public void testJJwt() {

            String id = UUID.randomUUID().toString();
            String issuer = "Baijing";
            String subject = "Happy Birthday";
            Long ttlMillis = (long) (1000 * 60 * 60 * 24);

            //The JWT signature algorithm we will be using to sign the token
            SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

            long nowMillis = System.currentTimeMillis();
            Date now = new Date(nowMillis);

            //We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("sdalfkjleiwfjioerjglni*^#&8dsfasdfrghtgru39847j*(&&^#*yr894yr8934thfklKNDhfiuerhfgoie8gorggkhsdlrghdsioghviosrhgvosrihtgor45ut9034759384509347328o5rh");
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        //Let's set the JWT Claims
        JwtBuilder builder = Jwts.builder().setId(id)
                .issuedAt(now)
                .subject(subject)
                .issuer(issuer)
                .signWith(signatureAlgorithm, signingKey);

        //if it has been specified, let's add the expiration
        if (ttlMillis >= 0) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        System.out.println(builder.compact());
        //Builds the JWT and serializes it to a compact, URL-safe string
//        return builder.compact();     // 去掉打印语句,能返回值
    }

代码 来源: https://web.archive.org/web/20230426235608/https://stormpath.com/blog/jwt-java-create-verify

How to Create and verify JWTs in Java

为何选择 JJwt 见 JSON Web Tokens - jwt.io 的 library ; 支持的比较健全。

解析令牌

import javax.xml.bind.DatatypeConverter;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.Claims;
 
//Sample method to validate and read the JWT
private void parseJWT(String jwt) {
 
    //This line will throw an exception if it is not a signed JWS (as expected)
    Claims claims = Jwts.parser()         
       .setSigningKey(DatatypeConverter.parseBase64Binary(apiKey.getSecret()))
       .parseClaimsJws(jwt).getBody();
    System.out.println("ID: " + claims.getId());
    System.out.println("Subject: " + claims.getSubject());
    System.out.println("Issuer: " + claims.getIssuer());
    System.out.println("Expiration: " + claims.getExpiration());
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值