JWT

1:依赖

 <!--jwt依赖-->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.0</version>
        </dependency>

2:生成JWT

  • 头这一部分使用默认,一半不需要改变
public String newJWT(){
        Calendar in=Calendar.getInstance();
        in.add(Calendar.SECOND,20);

        String token=JWT.create()
                .withClaim("id",1) //负载
                .withClaim("name","小黑")
                .withExpiresAt(in.getTime())  //令牌过期时间  20分钟
                .sign(Algorithm.HMAC256("!vbaiwyghasdk,zbqpoweuyr72346jkdab")); //密钥

        return token;
    }

3:验证JWT-拿数据

public void JWTTrue(){
        //创建验证对象
        JWTVerifier jwtVerifier=JWT.require(Algorithm.HMAC256("!vbaiwyghasdk,zbqpoweuyr72346jkdab")).build();//验签对象,需要知道加密的盐和算法
        //验证一个jwt,如果jwt没有问题,返回一个解码的jwt
        DecodedJWT verify=jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoi5bCP6buRIiwiaWQiOjEsImV4cCI6MTYxOTM1Mzc2NX0.uLn9Km_hiVxRkknYRiMutscvAPZyh_Z4aFgAQkkbGKk");

        System.out.println(verify.getClaim("id").asInt());
        System.out.println(verify.getClaim("name").asString());
    }
上一篇:Pi Network (Pi币、π币)手机认证教程


下一篇:Server returns invalid timezone. Go to ‘Advanced‘ tab and set ‘serverTimezone‘ property manually.