jwt 的签发 和 jwt 的验证

本文介绍了JWT(JSON Web Token)的签发和验证过程,使用了`java-jwt`库。首先展示了如何在`pom.xml`中引入依赖,然后通过示例代码详细说明了如何创建JWT,包括设置头部信息、签发者、过期时间等。接着,解释了JWT的验证步骤,包括解码JWT、验证签发者、ID和主题,并处理过期和无效的情况。最后,提供了完整的测试代码来运行签发和验证流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jwt 文档地址:https://github.com/auth0/java-jwt


pom.xml配置:

  <dependencies>
  <dependency>
   <groupId>com.auth0</groupId>
   <artifactId>java-jwt</artifactId>
   <version>3.2.0</version>
</dependency>
   </dependencies>


密匙:

  private static final byte[] SECRET="eyJhbGciPPBMiTKIckGciE0hm3orcuYdaceyJhbGciOiJI904467df11fff26d".getBytes();



jwt 的签发:

   public static String creatToken(){
String token = "";
Algorithm algorithm = Algorithm.HMAC256(SECRET);
  System.out.println(algorithm.getName());
Map<String,Object> headerClaims = new HashMap<>();
headerClaims.put("typ", "JWT");//声明类型
headerClaims.put("alg", "HS256");//声明加密的算法
Date date = new Date();//当期时间
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date ExpiresDate = null;
try {
ExpiresDate = dateFormat.parse("2018-05-04 12:34:23");
} catch (ParseException e) {
  e.printStackTrace();
}
    token = JWT.create()
  .withHeader(headerClaims)//头部
  .withIssuer("auth0dfdsfdsf")//jwt签发者
  .withIssuedAt(date)//jwt的签发时间
  .withExpiresAt(ExpiresDate)//jwt的过期时间,这个过期时间必须要大于签发时间
  .withJWTId("321321321321")//jwt的唯一身份标识,主要用来作为一次性token,从而回避重放攻击
// .withSubject("sfdf")//jwt所面向的用户
       .sign(algorithm);
System.out.println(token);
return token;
 
  }


jwt  验证:



public static void vaildToken(String token){
Algorithm algorithm = Algorithm.HMAC256(SECRET);
  DecodedJWT decodedJWT = JWT.decode(token);
  String Id = decodedJWT.getId();
  String Issuer = decodedJWT.getIssuer();
  String Payload = decodedJWT.getPayload();
  String Signature = decodedJWT.getSignature();
  String Subject = decodedJWT.getSubject();
   
  System.out.println("=======Id=========="+Id);
  System.out.println("=======Issuer=========="+Issuer);
  System.out.println("=======Payload=========="+Payload);
  System.out.println("======Signature=========="+Signature);
  System.out.println("======Subject==========="+Subject);
   
JWTVerifier verifier = JWT.require(algorithm)
       .withIssuer(Issuer)
       .withJWTId(Id)
       .withSubject(Subject)
         .build();  
try{
  DecodedJWT jwt = verifier.verify(token);
}catch(TokenExpiredException e){
System.out.println("+-=======时间过期==========");
e.printStackTrace();
}catch(InvalidClaimException e){
System.out.println("+-==========用户id验证失败=======");
e.printStackTrace();
}catch(Exception e){
System.out.println("+-==========验证失败=======");
e.printStackTrace();
}
}


测试:

public static void main(String[] args) {
String token = creatToken();
  vaildToken(token);

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值