java - 如何验证字符串是 JWT 令牌?
问题描述
在 Java 中,我们如何在不使用签名的情况下验证我给定的字符串是 JWT 令牌?
我在用
try {
return (new JwtConsumerBuilder()).setVerificationKey(SECRET_KEY).build().processToClaims(token);
} catch (InvalidJwtException var4) {
throw new IOException("Failed to parse");
}
这工作正常,但我想在没有SECRET_KEY
.
我只想验证它是否是 JWT 令牌。
解决方案
这是一个检查 JWT 结构的示例。您只需要添加 JWT 应该携带的数据的验证
boolean isJWT(String jwt) {
String[] jwtSplitted = jwt.split("\\.");
if (jwtSplitted.length != 3) // The JWT is composed of three parts
return false;
try {
String jsonFirstPart = new String(Base64.getDecoder().decode(jwtSplitted[0]));
JSONObject firstPart = new JSONObject(jsonFirstPart); // The first part of the JWT is a JSON
if (!firstPart.has("alg")) // The first part has the attribute "alg"
return false;
String jsonSecondPart = new String(Base64.getDecoder().decode(jwtSplitted[1]));
JSONObject secondPart = new JSONObject(jsonSecondPart); // The first part of the JWT is a JSON
//Put the validations you think are necessary for the data the JWT should take to validate
}catch (JSONException err){
return false;
}
return true;
}
推荐阅读
- c++ - 调用 'std::vector 没有匹配的函数
我正在解决的问题是:我必须采用T测试用例。对于每个测试用例,我必须将字符串作为输入,然后我需要将输入字符串排列为:偶数位置的字符串 {double space} 奇数位置的字符串(例如:输入- StackOverflow,输出- Sakvrlw t
- javascript - 异常捕获已禁用 - 无法捕获此异常
- sapui5 - 使用来自 json-string 的属性动态创建 UI5-Controls。json-string 中的事件问题
- ruby-on-rails - 如何在 Ruby on Rails 中的应用程序级别添加 toastr JS 通知
- java - DB和java时间日期比较和转换
- xpath - 如何在 IIB 的图形映射节点的自定义 XPath 中创建 if else 函数?
- c++ - 是否可以设置在条件有效的任何地方评估的“全局”条件断点?
- ubuntu - 如何在 Ubuntu 16.04.6 中设置允许 Grafana 绑定到端口 80?
- r - 将 Plotly 预测图转换为 ggplot 图
- javascript - 使用反应动画多个文本