简体   繁体   English

如何验证字符串是 JWT 令牌?

[英]How to verify that a string is JWT token?

In Java How can we verify that i given String is a JWT Token without using Signature?在 Java 中,我们如何验证我给定的字符串是 JWT 令牌而不使用签名?

I am using我在用

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

This works fine but I want to verify this without SECRET_KEY .这工作正常,但我想在没有SECRET_KEY的情况下验证这一点。

I Just want to verify whether it is a JWT token or not.我只是想验证它是否是 JWT 令牌。

Here is an example to check the structure of the JWT.这是检查 JWT 结构的示例。 You only need to add the validations of the data that the JWT should carry您只需添加 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;
    }

You can decode JWT from base64 and check necessarily field.您可以从 base64 解码 JWT 并检查必要的字段。 Or simply check token, why you want verify it, It's not faster then simpy check it.或者只是检查令牌,为什么要验证它,它并不比简单检查它更快。

Try this one.试试这个。

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

Next You need to get from jwt body this part which is important for You eg.接下来,您需要从 jwt 正文中获取这对您很重要的部分,例如。

JSONObject body = JWTUtils.getPayload(token);
        String username = body.getString("username");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM