如何验证一个字符串是否为JWT令牌?

5

在Java中,如何验证给定的字符串是JWT Token而不使用Signature?

我正在使用

try {
     return (new JwtConsumerBuilder()).setVerificationKey(SECRET_KEY).build().processToClaims(token);
} catch (InvalidJwtException var4) {
     throw new IOException("Failed to parse");
}  

这可以正常工作,但我想在没有 "SECRET_KEY" 的情况下验证它。
我只是想验证它是否为JWT令牌。
3个回答

6

以下是一个示例,用于检查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;
    }

这对我起作用了。 - sumit kumar

1

试试这个。

  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");

-1

您可以从base64解码JWT并检查必要的字段。或者只需检查令牌,为什么要验证它,这不比简单检查它更快。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接