首页 > 解决方案 > 如何验证字符串是 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 令牌。

标签: javajwt

解决方案


这是一个检查 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;
    }

推荐阅读