我使用的是JWT令牌,我声称其中一个是ByteBuffer。 JWT生成成功,但是当我尝试解析JWT令牌并验证声明时,它会抱怨claimSet没有值。
以下是我的代码的外观:
ByteBuffer encryptedText = getEncryptedTextAsByteBuffer();
Instant timestamp = timestampSupplier.get();
JWTClaimsSet claimsSet = new JWTClaimsSet();
claimsSet.setAudience("test-audience");
claimsSet.setIssuer("test-issuer");
claimsSet.setNotBeforeTime(Date.from(timestamp));
claimsSet.setExpirationTime(Date.from(Instant.ofEpochSecond(expirationTimestamp)));
claimsSet.setClaim("myObject", encryptedText );
PlainJWT jwt = new PlainJWT(claimsSet);
return jwt.serialize();
验证码如下所示:
PlainJWT jwtToken = PlainJWT.parse(jwtToken);
ReadOnlyJWTClaimsSet claimsSet = jwtToken.getJWTClaimsSet();
Map<String, Object> claims = claimsSet.getAllClaims();
ByteBuffer encryptedText = (ByteBuffer) claims.get("myObject");
我看到的异常消息是:
java.lang.ClassCastException: net.minidev.json.JSONObject cannot be cast to java.nio.ByteBuffer
我添加了一个调试器,看到Jwt生成有一个有效的非空ByteBuffer,但结果声明有&#34; myObject&#34; key,但值为空json String。我们可以不将声明用作byteBuffer吗?或者我做错了什么?
任何帮助都将不胜感激。
答案 0 :(得分:1)
ByteBuffer包含二进制数据,但JSON是文本格式。您需要将基础字节数组编码为base64,并将其包含为JWT的声明
我对ByteBuffer很新,所以我查看了javadoc以了解它是如何工作的。请试试这个
// ByteBuffer to base64
byte[] data = new byte[encryptedText.remaining()]
encryptedText.get(data);
String dataB64 = DataTypeConverter.printBase64Binary(data);
//Add claim
claimsSet.setClaim("myObject", dataB64);
要验证它,请从base64转换为byte []。我认为在这种情况下不需要ByteBuffer,但你可以从byte []
构建它 String dataB64 = (String) claims.get("myObject");
byte data[] = DataTypeConverter.parseBase64Binary(dataB64)
答案 1 :(得分:0)
答案有帮助。这是我为使代码工作所做的修改:
ByteBuffer encryptedText = getEncryptedTextAsByteBuffer();
String encodedText = Base64.getEncoder().encodeToString(encryptedText .array());
Instant timestamp = timestampSupplier.get();
JWTClaimsSet claimsSet = new JWTClaimsSet();
claimsSet.setAudience("test-audience");
claimsSet.setIssuer("test-issuer");
claimsSet.setNotBeforeTime(Date.from(timestamp));
claimsSet.setExpirationTime(Date.from(Instant.ofEpochSecond(expirationTimestamp)));
claimsSet.setClaim("myObject", );
PlainJWT jwt = new PlainJWT(claimsSet);
return jwt.serialize();
验证部分已更改为:
PlainJWT jwtToken = PlainJWT.parse(jwtToken);
ReadOnlyJWTClaimsSet claimsSet = jwtToken.getJWTClaimsSet();
String claim = (String)claimsSet.getClaim("myObject");
byte[] emailBinary = Base64.getDecoder().decode(claim);