【问题标题】:How to verify that a string is JWT token?如何验证字符串是 JWT 令牌?
【发布时间】:2020-05-22 21:55:23
【问题描述】:

在 Java 中我们如何在不使用签名的情况下验证我给定的字符串是 JWT 令牌?

我正在使用

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

这工作正常,但我想在没有SECRET_KEY 的情况下验证这一点。

我只是想验证它是否是 JWT 令牌。

【问题讨论】:

    标签: java jwt


    【解决方案1】:

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

    【讨论】:

    • 这对我有用
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      试试这个。

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

      【讨论】:

        猜你喜欢
        • 2018-10-16
        • 2020-03-07
        • 2019-06-23
        • 2017-02-20
        • 2016-12-02
        • 2022-10-15
        • 2017-07-27
        • 2019-10-20
        • 2016-01-17
        相关资源
        最近更新 更多