在Java中,如何在不使用签名的情况下验证给定的String是JWT令牌?
我正在使用
try {
return (new JwtConsumerBuilder()).setVerificationKey(SECRET_KEY).build().processToClaims(token);
} catch (InvalidJwtException var4) {
throw new IOException("Failed to parse");
}
这工作正常,但我想在没有SECRET_KEY
的情况下进行验证。
我只想验证它是否是JWT令牌。
答案 0 :(得分:0)
您可以从base64解码JWT并检查必填字段。或只是简单地检查令牌,为什么要验证令牌,而不是简单地检查令牌。
答案 1 :(得分:0)
尝试这个。
public static JSONObject getPayload(String jwt) {
try {
Base64.Decoder dec = Base64.getDecoder();
final String payload = jwt.split(SecurityConstants.SPLIT_SLASH)[PAYLOAD];
final byte[] sectionDecoded = dec.decode(payload);
final String jwtSection = new String(sectionDecoded, SecurityConstants.CODE_PAGE);
return new JSONObject(jwtSection);
} catch (final UnsupportedEncodingException e) {
throw new InvalidParameterException(e.getMessage());
} catch (final Exception e) {
throw new InvalidParameterException(SecurityConstants.ERROR_IN_PARSING_JSON);
}
}
下一步,您需要从jwt主体中获取这对您来说很重要的部分,例如。
JSONObject body = JWTUtils.getPayload(token);
String username = body.getString("username");
答案 2 :(得分:0)
这里是检查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;
}