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/