Validates a JWT token.
@param secret secret used for generating the token
@param jwt token to validate
@return true if token is valid
321671
public static boolean isValidJWToken(String secret, SignedJWT jwt) {
		try {
			if (secret != null && jwt != null) {
				JWSVerifier verifier = new MACVerifier(secret);
				if (jwt.verify(verifier)) {
					Date referenceTime = new Date();
					JWTClaimsSet claims = jwt.getJWTClaimsSet();

					Date expirationTime = claims.getExpirationTime();
					Date notBeforeTime = claims.getNotBeforeTime();
					boolean expired = expirationTime == null || expirationTime.before(referenceTime);
					boolean notYetValid = notBeforeTime == null || notBeforeTime.after(referenceTime);

					return !(expired || notYetValid);
				}
			}
		} catch (JOSEException e) {
			logger.warn(null, e);
		} catch (ParseException ex) {
			logger.warn(null, ex);
		}
		return false;
	}
117323
public
    static function validate($uuid, $secret)
    {
        $uuidData = preg_replace('/[^0-9a-z]/i', '', $uuid);
        $uuidData = substr($uuidData, 8);

        $hash = hash_hmac(self::HASH_METHOD, $uuidData, $secret);
        $checksum = "b" . substr($hash, 0, 7);

        return $checksum == substr($uuid, 0, 8);
    }
118131
public boolean isCredentialsValid(String username, String password) {
        try {
            String token = getTokenAuthenticationManager().login(StringUtil.toEmptyIfNull(username), StringUtil.toEmptyIfNull(password));
            getTokenAuthenticationManager().logout(token);

            return true;
        } catch (Exception ex) {
            return false;
        }
    }
517839
@JsonIgnore
    public boolean isValid() {
        if (kty == null) {
            return false;
        }

        if (keyOps != null) {
            final Set<JsonWebKeyOperation> set = new HashSet<JsonWebKeyOperation>(JsonWebKeyOperation.ALL_OPERATIONS);
            for (int i = 0; i < keyOps.size(); i++) {
                if (!set.contains(keyOps.get(i))) {
                    return false;
                }
            }
        }

        if (JsonWebKeyType.OCT.equals(kty)) {
            return isValidOctet();
        } else if (JsonWebKeyType.RSA.equals(kty)) {
            return isValidRsa();
        } else if (JsonWebKeyType.RSA_HSM.equals(kty)) {
            return isValidRsaHsm();
        } else if (JsonWebKeyType.EC.equals(kty)) {
            return isValidEc();
        } else if (JsonWebKeyType.EC_HSM.equals(kty)) {
            return isValidEcHsm();
        }

        return false;
    }
168874
public final boolean isValid(HttpServletRequest req, String token) {
		String storedToken = getStoredToken(req);
		
		if (storedToken == null)
			return false;
		
		return storedToken.equals(token);
	}
916037
public boolean isValid(String apiKey) throws HelloSignException {
        if (apiKey == null || apiKey == "") {
            return false;
        }
        try {
            Mac sha256HMAC = Mac.getInstance(HASH_ALGORITHM);
            SecretKeySpec secretKey = new SecretKeySpec(apiKey.getBytes(), HASH_ALGORITHM);
            sha256HMAC.init(secretKey);
            String data = String.valueOf(getLong(EVENT_TIME)) + getType();
            String computedHash = bytesToHex(sha256HMAC.doFinal(data.getBytes()));
            String providedHash = getString(EVENT_HASH);
            return computedHash.equalsIgnoreCase(providedHash);
        } catch (InvalidKeyException e) {
            throw new HelloSignException("Invalid API Key (" + e.getMessage() + "): " + apiKey);
        } catch (IllegalArgumentException e) {
            throw new HelloSignException("Invalid API Key (" + e.getMessage() + "): " + apiKey);
        } catch (NoSuchAlgorithmException e) {
            throw new HelloSignException("Unable to process API key", e);
        }
    }
1127129
public static String getTotp(String secret) {
        Objects.requireNonNull(secret, Required.SECRET.toString());
        
        String value = null;
        try {
            TOTP builder = TOTP.key(secret.getBytes(StandardCharsets.US_ASCII.name()))
                    .timeStep(TimeUnit.SECONDS.toMillis(PERIOD))
                    .digits(DIGITS)
                    .hmacSha(ALGORITHM)
                    .build();
            
            value = builder.value();
        } catch (UnsupportedEncodingException e) {
            LOG.error("Failed to create TOTP",  e);
        }
        
        return value;
    }
927208
public static boolean verifySignature(EnumMap<FacebookParam, CharSequence> params, String secret,
                                        String expected) {
    assert !(null == secret || "".equals(secret));
    if (null == params || params.isEmpty() )
      return false;
    if (null == expected || "".equals(expected)) {
      return false;
    }
    params.remove(FacebookParam.SIGNATURE);
    List<String> sigParams = convertFacebookParams(params.entrySet());
    return verifySignature(sigParams, secret, expected);
  }
1125799
public static boolean hasValidAuthentication(String cookie) {
        boolean valid = false;
        if (StringUtils.isNotBlank(cookie)) {
            Config config = Application.getInstance(Config.class);

            String value = null;
            String [] contents = cookie.split(";");
            for (String content : contents) {
                if (StringUtils.isNotBlank(content) && content.startsWith(config.getAuthenticationCookieName())) {
                    value = StringUtils.substringAfter(content, config.getAuthenticationCookieName() + "=");
                    value = PATTERN.matcher(value).replaceAll("");
                }
            }
            
            if (StringUtils.isNotBlank(value)) {
                String jwt = Application.getInstance(Crypto.class).decrypt(value, config.getAuthenticationCookieEncryptionKey());
                
                JwtConsumer jwtConsumer = new JwtConsumerBuilder()
                        .setRequireExpirationTime()
                        .setRequireSubject()
                        .setVerificationKey(new HmacKey(config.getAuthenticationCookieSignKey().getBytes(StandardCharsets.UTF_8)))
                        .setJwsAlgorithmConstraints(new AlgorithmConstraints(ConstraintType.WHITELIST, AlgorithmIdentifiers.HMAC_SHA512))
                        .build();
                try {
                    jwtConsumer.processToClaims(jwt);
                    valid = true;
                } catch (InvalidJwtException e) {
                    LOG.error("Failed to parse authentication cookie", e);
                }
            }
        }
        
        return valid;
    }
892378
@SneakyThrows
    public static String decryptJwtValue(final Key secretKeyEncryptionKey, final String value) {
        val jwe = new JsonWebEncryption();
        jwe.setKey(secretKeyEncryptionKey);
        jwe.setCompactSerialization(value);
        LOGGER.trace("Decrypting value...");
        try {
            return jwe.getPayload();
        } catch (final JoseException e) {
            if (LOGGER.isTraceEnabled()) {
                throw new DecryptionException(e);
            }
            throw new DecryptionException();
        }
    }
569581
function validateAskPermission (token) {
  const header = jwt.decode(token)

  return validateToken(token) && header[ASK_CLAIM_KEY]
}
125662
public static Map<String, Object> verify(String token, final RSAPublicKey pk) throws InvalidTokenException {
        // RS256签名验证器
        Verifier verifier = new Verifier() {
            @Override
            public boolean verifySignature(String content, String payload, String signature) {
                return JWT.verifySignature(content,signature,pk);
            }
        };
        return verify(token, verifier);
    }
1112628
protected void validateCredentials(final UsernamePasswordCredentials credentials,
                                       final OAuthRegisteredService registeredService,
                                       final WebContext context) {
        if (!OAuth20Utils.checkClientSecret(registeredService, credentials.getPassword())) {
            throw new CredentialsException("Bad secret for client identifier: " + credentials.getPassword());
        }
    }
742464
public final boolean isValidPasswordResetToken(String token) {
		Sysprop s = CoreUtils.getInstance().getDao().read(getAppid(), identifier);
		return isValidToken(s, Config._RESET_TOKEN, token);
	}
241085
private static boolean validateToken(String originalToken, String storedToken) throws NoSuchAlgorithmException, InvalidKeySpecException {
    String[] parts = storedToken.split(":");
    int iterations = Integer.parseInt(parts[0]);
    byte[] salt = fromHex(parts[1]);
    byte[] hash = fromHex(parts[2]);

    PBEKeySpec spec = new PBEKeySpec(originalToken.toCharArray(), salt, iterations, hash.length * 8);
    SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    byte[] testHash = skf.generateSecret(spec).getEncoded();

    int diff = hash.length ^ testHash.length;
    for (int i = 0; i < hash.length && i < testHash.length; i++) {
      diff |= hash[i] ^ testHash[i];
    }
    return diff == 0;
  }
233357
public static function validate(string $token, string $secret): bool
    {
        $parse = self::parser($token, $secret);

        if (!self::validateWithExpiration($parse)) {
            return false;
        }

        if (!self::validateNotBefore($parse)) {
            return false;
        }

        return true;
    }
1129794
public static function csrfTokenValidate($secret, $user, $token)
    {
        $tokenParts = explode('-', $token);
        if (count($tokenParts) !== 2) {
            return false;
        }

        list($timeValidFor, $hash) = $tokenParts;

        $hashedSecret = hash('sha512', $secret);
        $dataToHash = sprintf('%s-%s-%s', $hashedSecret, $user, $timeValidFor);
        $newHash = static::hashFunction($dataToHash);
        if ($newHash !== $hash) {
            return false;
        }
        if (time() > $timeValidFor) {
            return false;
        }

        return true;
    }