Validates a JWT by ensuring the signature matches and validates
against the SecretKey and checks the expiration date.

@param token the token to validate
@return true if validation successful, false if not
@since 1.0.0
189701
public boolean validateToken(final String token) {
        try {
            final JwtParser jwtParser = Jwts.parser().setSigningKey(key);
            jwtParser.parse(token);
            this.subject = jwtParser.parseClaimsJws(token).getBody().getSubject();
            this.expiration = jwtParser.parseClaimsJws(token).getBody().getExpiration();
            return true;
        } catch (SignatureException e) {
            LOGGER.info(SecurityMarkers.SECURITY_FAILURE, "Received token that did not pass signature verification");
        } catch (ExpiredJwtException e) {
            LOGGER.debug(SecurityMarkers.SECURITY_FAILURE, "Received expired token");
        } catch (MalformedJwtException e) {
            LOGGER.debug(SecurityMarkers.SECURITY_FAILURE, "Received malformed token");
            LOGGER.debug(SecurityMarkers.SECURITY_FAILURE, e.getMessage());
        } catch (UnsupportedJwtException | IllegalArgumentException e) {
            LOGGER.error(SecurityMarkers.SECURITY_FAILURE, e.getMessage());
        }
        return false;
    }
607260
public JsonObject validateTokenToJson(String token) throws GitkitClientException {
    if (token == null) {
      return null;
    }
    try {
      return tokenHelper.verifyAndDeserialize(token).getPayloadAsJsonObject();
    } catch (SignatureException e) {
      throw new GitkitClientException(e);
    }
  }
501148
public static boolean isValid(AppIdToken appIdToken, String appId, String token) {
        if (appIdToken == null || StringUtil.isEmpty(appId) || StringUtil.isEmpty(token)) {
            return false;
        }
        return appIdToken.appId.equals(appId) && appIdToken.token.equals(token);
    }
574306
@GET
    @Path("/validate/{token}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response validateAccount(@PathParam("token") String token) {
        try{
            if (authServerLogic.validateAccount(token)) {
                return Response.ok().build();
            } else {
                return Response.status(Status.NOT_FOUND).build();
            }
        }catch (ServerDAO.DAOException e) {
            return fromDAOExpection(e);
        }
    }
78064
def verify_token(self, token) -> bool:
        
        try:
            self.data = jwt.decode(Security.decrypt(token), self.app_secret)
            return True
        except (Exception, BaseException) as error:
            self.errors.append(error)
            return False
        return False
107409
public function validateToken($token)
    {
        // The token must match of course.
        if ($this->Token != $token) {
            return false;
        }

        // Has the token expired?
        if (strtotime($this->TokenExpiry) < time()) {
            return false;
        }

        $hashProvider = HashProvider::getProvider();
        return $hashProvider->compareHash($this->getSavedPasswordTokenData(), $token);
    }
984663
private static boolean checkTokenValid(final char[] token) {
        if (token == null || token.length == 0) {
            return true;
        }
        for (int i = 0; i < token.length; i++) {
            if (token[i] == '\n') {
                return false;
            }

        }
        return true;
    }
1117254
public static boolean isValidNmtoken(String nmtoken) {
    final int length = nmtoken.length();
    if (length == 0) {
      return false;
    }
    for (int i = 0; i < length; ++i) {
      char ch = nmtoken.charAt(i);
      if (!isName(ch)) {
        return false;
      }
    }
    return true;
  }
689644
protected void validateSignature(ConsumerAuthentication authentication) throws AuthenticationException {
    SignatureSecret secret = authentication.getConsumerDetails().getSignatureSecret();
    String token = authentication.getConsumerCredentials().getToken();
    OAuthProviderToken authToken = null;
    if (token != null && !"".equals(token)) {
      authToken = getTokenServices().getToken(token);
    }

    String signatureMethod = authentication.getConsumerCredentials().getSignatureMethod();
    OAuthSignatureMethod method;
    try {
      method = getSignatureMethodFactory().getSignatureMethod(signatureMethod, secret, authToken != null ? authToken.getSecret() : null);
    }
    catch (UnsupportedSignatureMethodException e) {
      throw new OAuthException(e.getMessage(), e);
    }

    String signatureBaseString = authentication.getConsumerCredentials().getSignatureBaseString();
    String signature = authentication.getConsumerCredentials().getSignature();
    if (log.isDebugEnabled()) {
      log.debug("Verifying signature " + signature + " for signature base string " + signatureBaseString + " with method " + method.getName() + ".");
    }
    method.verify(signatureBaseString, signature);
  }
52381
public Date getExpirationDateFromToken(String token) {
        Date expiration;
        try {
            final Claims claims = getClaimsFromToken(token);
            return claims.getExpiration();
        } catch (Exception e) {
            log.error("get expiration Time from jwt token error : {}", e.getMessage());
            return null;
        }
    }
562131
public static boolean checkSignature(String token, String signature,
                                         String timestamp, String nonce) {
        if (hasBlank(token, signature, timestamp, nonce)) {
            return false;
        }
        String[] arr = new String[]{token, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (String anArr : arr) {
            content.append(anArr);
        }
        MessageDigest md;
        String tmpStr = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes("UTF-8"));
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            LOG.error("加密方式异常", e);
        } catch (UnsupportedEncodingException e) {
            LOG.error("编码格式不支持", e);
        }
        return tmpStr != null && tmpStr.equalsIgnoreCase(signature);
    }
1368050
public boolean validateIDToken(String idToken) throws OpenIdException {
        
        logger.debug("Enter OAuth2PlatformClient::validateIDToken");
        
        String[] idTokenParts = idToken.split("\\.");
        
        if (idTokenParts.length < 3) {
            logger.debug("invalid idTokenParts length");
            return false;
        }

        String idTokenHeader = base64UrlDecode(idTokenParts[0]);
        String idTokenPayload = base64UrlDecode(idTokenParts[1]);
        byte[] idTokenSignature = base64UrlDecodeToBytes(idTokenParts[2]);

        JSONObject idTokenHeaderJson = new JSONObject(idTokenHeader);
        JSONObject idTokenHeaderPayload = new JSONObject(idTokenPayload);

        //Step 1 : First check if the issuer is as mentioned in "issuer" in the discovery doc
        String issuer = idTokenHeaderPayload.getString("iss");
        if(!issuer.equalsIgnoreCase(oauth2Config.getIntuitIdTokenIssuer())) {
            logger.debug("issuer value mismtach");
            return false;
        }

        //Step 2 : check if the aud field in idToken is same as application's clientId
        JSONArray jsonaud = idTokenHeaderPayload.getJSONArray("aud"); 
        String aud = jsonaud.getString(0);

        if(!aud.equalsIgnoreCase(oauth2Config.getClientId())) {
            logger.debug("incorrect client id");
            return false;
        }

        //Step 3 : ensure the timestamp has not elapsed
        Long expirationTimestamp = idTokenHeaderPayload.getLong("exp");
        Long currentTime = System.currentTimeMillis() / 1000; 

        if((expirationTimestamp - currentTime) <= 0) {
            logger.debug("expirationTimestamp has elapsed");
            return false;
        }

        //Step 4: Verify that the ID token is properly signed by the issuer
        HashMap<String,JSONObject> keyMap = getKeyMapFromJWKSUri();
        if (keyMap == null || keyMap.isEmpty()) {
            logger.debug("unable to retrive keyMap from JWKS url");
            return false;
        }
        
        //first get the kid from the header.
        String keyId = idTokenHeaderJson.getString("kid");
        JSONObject keyDetails = keyMap.get(keyId);

        //now get the exponent (e) and modulo (n) to form the PublicKey
        String exponent = keyDetails.getString("e");
        String modulo = keyDetails.getString("n");

        //build the public key
        PublicKey publicKey = getPublicKey(modulo, exponent);

        byte[] data = (idTokenParts[0] + "." + idTokenParts[1]).getBytes(StandardCharsets.UTF_8);

        try {
            //verify token using public key
            boolean isSignatureValid = verifyUsingPublicKey(data, idTokenSignature, publicKey);
            logger.debug("isSignatureValid: " + isSignatureValid);
            return isSignatureValid;
           
        } catch (GeneralSecurityException e) {
            logger.error("Exception while validating ID token ", e);
            throw new OpenIdException(e.getMessage(), e);
        }

    }
939434
protected synchronized void cacheToken(final Token token) {

		log.debug("OAuthTokenManager.cacheToken");

		// Parse token expires in seconds.
		int tokenExpiresInSecs;
		try {
			tokenExpiresInSecs = Integer.parseInt(token.getExpires_in());
		} catch (NumberFormatException exception) {
			tokenExpiresInSecs = 0;
		}

		// Parse token expiration time
		long tokenExpirationTime;
		try {
			tokenExpirationTime = Long.parseLong(token.getExpiration());
		} catch (NumberFormatException exception) {
			tokenExpirationTime = 0;
		}

		// Calculate token refresh time based on lifespan percentage offset.
		long refreshBeforeExpirySecs = (long) (tokenExpiresInSecs * this.iamRefreshOffset);
		long tokenRefreshTime = tokenExpirationTime - refreshBeforeExpirySecs;

		token.setRefreshTime(tokenRefreshTime);
		token.setExpirationTime(tokenExpirationTime);

		setTokenCache(token);
	}
68999
private static boolean isTokenNtlm(final byte[] token) {
        if (token == null || token.length < NTLM_TOKEN_MAX_LENGTH) {
            return false;
        }
        return IntStream.range(0, NTLM_TOKEN_MAX_LENGTH).noneMatch(i -> NTLMSSP_SIGNATURE[i] != token[i]);
    }
1161016
function verify(token, sign, options) {
  return (done) => {
    jwt.verifySync(token, sign, options, done);
  };
}
168874
public final boolean isValid(HttpServletRequest req, String token) {
		String storedToken = getStoredToken(req);
		
		if (storedToken == null)
			return false;
		
		return storedToken.equals(token);
	}
744036
private static boolean verifySignature(String content, String signed, RSAPublicKey pk) throws InvalidTokenException {
        try {
            byte[] signedData = Base64.urlDecode(signed);
            byte[] contentData = content.getBytes(JWT.UTF_8);

            Signature signature = Signature.getInstance(ALG_SHA256WITHRSA);
            signature.initVerify(pk);
            signature.update(contentData);

            return signature.verify(signedData);
        }catch (SignatureException e) {
            throw new InvalidTokenException("Invalid signature", e);
        }catch (Exception e) {
            throw new RuntimeException("Verify signature error", e);
        }
    }