jwt生成和解密-jose4j

本文展示了如何利用jose4j库生成和校验JWT。通过创建RsaJsonWebKey生成JWT,设置claims,然后使用私钥签名。验证过程包括设置预期的issuer、audience,使用公钥进行签名验证。代码示例包含了生成公钥和私钥的存储与读取方法,并提供了一个在线JWT测试网站链接。
摘要由CSDN通过智能技术生成

jwt生成和解密-jose4j

jwt的概念和生成意义在这里就不描述了,百度能搜到很多,直接上代码

官网地址

https://bitbucket.org/b_c/jose4j/wiki/Home

maven

<dependency>
    <groupId>org.bitbucket.b_c</groupId>
    <artifactId>jose4j</artifactId>
    <version>0.9.3</version>
  </dependency>
生成jwt 地址
   	RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
      rsaJsonWebKey.setKeyId("k1");
      JwtClaims claims = new JwtClaims();
      claims.setIssuer("xizi");
      claims.setAudience("allUser");
      claims.setExpirationTimeMinutesInTheFuture(1);
      claims.setGeneratedJwtId();
      claims.setIssuedAtToNow();
      claims.setNotBeforeMinutesInThePast(1);
      claims.setSubject("admin");
      claims.setClaim("home", "喜子开发平台");
      String[] claim = {"group", "admin"};
      claims.setStringListClaim("group", Arrays.asList(claim));
      JsonWebSignature jws = new JsonWebSignature();
      jws.setPayload(claims.toJson());
      jws.setKey(rsaJsonWebKey.getPrivateKey());
      jws.setKeyIdHeaderValue(rsaJsonWebKey.getKeyId());
      jws.setAlgorithmHeaderValue(AlgorithmIdentifiers.RSA_PSS_USING_SHA256);
      String jwt = jws.getCompactSerialization();
      log.info("jwt {}", jwt);
      toByte(rsaJsonWebKey.getKey());
     

注意最后的这个代码是为了生成公钥的,一会用来验证,否则不会验证成功的,此处先保存到本地
toByte(rsaJsonWebKey.getKey());

校验代码
     String jwt = "eyJraWQiOiJrMSIsImFsZyI6IlBTMjU2In0.eyJpc3MiOiJ4aXppIiwiYXVkIjoiYWxsVXNlciIsImV4cCI6MTY4MTM5Mjg4MCwianRpIjoicFpSbGxubC11aDUxal9RS3ctZ1RBdyIsImlhdCI6MTY4MTM5MjgyMCwibmJmIjoxNjgxMzkyNzYwLCJzdWIiOiJhZG1pbiIsImVtYWlsIjoiYmozNTczNDkxQHNpbmEuY29tIiwiZ3JvdXAiOlsiZ3JvdXAiLCJhZG1pbiJdfQ.R2gGhlcuXtNLp5f-u_GAobh_XXLHUH0IC_QdVGEmxlnbhlY0gjPLeeb8w1aAQvJ1Y7VqCd-flYR2GxHa2M0LAbpyR_8S5jCZTTnznH0GrsBUcvJY8oEEHwny3fOAVMmAj8ms840qbeNz4Ib9i1w_zQten7hEXAU-6fhD9cKms6ji5tglu9p5nYaF0ugbcyi41kDAUqjDtCTncskEXiifgwAkbDeWADzRSmtVm0MwjT_xBu1dqDYMbPnz0jHHraL-67e0cfTurEKhjQiOZ6DjGQsusMcjlhRzD2CwPPULAHQQcwODld87nlmBI8SxnjqmA8iIMvTX2ZQbas_YI98Xtg";

        RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);
        rsaJsonWebKey.setKeyId("k1");
        JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                .setRequireExpirationTime() // the JWT must have an expiration time
                .setAllowedClockSkewInSeconds(1) // allow some leeway in validating time based claims to account for clock skew
                .setRequireSubject() // the JWT must have a subject claim
                .setExpectedIssuer("xizi") // whom the JWT needs to have been issued by
                .setExpectedAudience("allUser") // to whom the JWT is intended for
                .setVerificationKey(read()) // verify the signature with the public key
                .setJwsAlgorithmConstraints( // only allow the expected signature algorithm(s) in the given context
                        AlgorithmConstraints.ConstraintType.PERMIT, AlgorithmIdentifiers.RSA_PSS_USING_SHA256) // which is only RS256 here
                .build(); // create the JwtConsumer instance

        try {
            //  Validate the JWT and process it to the Claims
            JwtClaims jwtClaims = jwtConsumer.processToClaims(jwt);
            log.info("JWT validation succeeded! {}" ,jwtClaims.toJson());
        } catch (InvalidJwtException e) {
            log.error("Invalid JWT! {}", e.getMessage());

            if (e.hasExpired()) {
                log.error("JWT expired at {}" ,e.getJwtContext().getJwtClaims().getExpirationTime());
            }

            if (e.hasErrorCode(ErrorCodes.AUDIENCE_INVALID)) {
                log.error("JWT had wrong audience: {}" + e.getJwtContext().getJwtClaims().getAudience());
            }
        }

基本就是摘抄的官网的,大家可以去官网看看
此处就看可以看到验证成功还是失败了

注意这个方法 read()) 是为了读取上个方法存的公钥

下面是存公钥 和读公钥的方法,实际项目中不用这个存,这个就是为了测试用用
    public void toByte(Key key) throws IOException {
        FileOutputStream out = new FileOutputStream("key");
        ObjectOutputStream oo = new ObjectOutputStream(out);
        oo.writeObject(key);
        oo.flush();
        oo.close();
    }

    public Key read() throws IOException, ClassNotFoundException {
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("key"));
        Key key = (Key) (in.readObject());
        in.close();
        return key;
    }

最后

生成的jwt可以到这个网站测试一下

网址 https://jwt.io/

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值