Verifying Hook Request. If signing secret is not defined or fails fallback to api call.

@throws WebapiException
@throws \Magento\Framework\Exception\LocalizedException
497004
public function verifyWebhook()
    {
        $payload     = $this->request->getContent();
        $hmac_header = $this->request->getHeader(self::HMAC_HEADER);

        if (!$this->verifyWebhookSecret($payload, $hmac_header) && !$this->verifyWebhookApi($payload, $hmac_header)) {
            throw new WebapiException(__('Precondition Failed'), 6001, 412);
        }
    }
948196
public function parse(): Payload
    {
        /** Check signature from header */
        if (!$this->_checkSignature()) {
            throw new BadSignatureException('Hook secret does not match.');
        }

        /** Get data from different locations according to content-type */
        switch ($this->serverBag->get('CONTENT_TYPE')) {
            case 'application/json':
                $data = $this->getRawData();
                break;

            case 'application/x-www-form-urlencoded':
                $data = $_POST['payload'];
                break;

            default:
                throw new Exception('Unsupported content type: "' . $this->serverBag->get('CONTENT_TYPE') . '"');
        }
        $this->setParsedData($data);

        return $this;
    }
886758
public function onAuthenticationFailure( Request $request, AuthenticationException $exception )
	{
		// if AJAX login
		if ( ! $request->isXmlHttpRequest() ) {
			throw new NotFoundHttpException('Must use AJAX Login');
		}

		return new JsonResponse(array(
				"success" => false
		));
	}
1278673
private <TResponse> TResponse callGetApi(
            BasicCredentials credentials, String path, Map<String, String> queryParams,
            Class<TResponse> responseClass) throws AuthleteApiException
    {
        return callApi(HttpMethod.GET, credentials, path, queryParams, (Object)null, responseClass);
    }
327551
public function verify(Token $token, VerificationContext $verificationContext = null): void
    {
        if (null === $verificationContext) {
            $verificationContext = new VerificationContext($this->getEncryption());
        }

        if ($this->getAudience()) {
            $verificationContext->setAudience($this->getAudience());
        }

        try {
            $this->getLib()->verify($token, $verificationContext);
        } catch (\Exception $exception) {
            throw new VerifyTokenException('Token did not pass the verification', $exception->getCode(), $exception);
        }
    }
211146
def sign(self, consumer_secret, method, url, oauth_token_secret=None,
             **params):
        """"""
        key = self._escape(consumer_secret) + b'&'
        if oauth_token_secret:
            key += self._escape(oauth_token_secret)
        return key.decode()
117103
private void checkAuthorization(Action action) throws NotAuthorizedException {
		@SuppressWarnings("unchecked")
		Map<String, List<String>> httpHeaders = (Map<String, List<String>>) wsContext.getMessageContext().get(MessageContext.HTTP_REQUEST_HEADERS);
		String clientApplicationName = httpHeaders.get(APPSENSOR_CLIENT_APPLICATION_IDENTIFIER_ATTR).get(0);

		ClientApplication clientApplication = appSensorServer.getConfiguration().findClientApplication(clientApplicationName);
		
		org.owasp.appsensor.core.accesscontrol.Context context = new org.owasp.appsensor.core.accesscontrol.Context();
		
		appSensorServer.getAccessController().assertAuthorized(clientApplication, action, context);
	}
618019
function checkApiKey(key) {
  if (!GLOBAL.config.apis || !GLOBAL.config.apis[key]) {
    GLOBAL.error('no GLOBAL.config.apis.bing');
    return false;
  }
  return true;
}
718326
public function validateAndParseWebhookNotificationFromRequest(\Symfony\Component\HttpFoundation\Request $request) {
        $json_data = json_decode($request->getContent(), true);
        if (!is_array($json_data)) { throw new AuthorizationException("Invalid webhook data received"); }

        // make sure the message is signed properly
        //   throws an exception if invalid
        $this->validateWebhookNotification($json_data);

        return $this->parseWebhookNotificationData($json_data);
    }
12553
private static boolean verifySignature(String content, String secret, String signature) throws InvalidTokenException{
        try {
            SecretKey secretKey = new SecretKeySpec(secret.getBytes(), ALG_HMACSHA256);
            Mac mac = Mac.getInstance(ALG_HMACSHA256);
            mac.init(secretKey);
            byte[] bytes = mac.doFinal(content.getBytes());
            String base64 = base64UrlEncode(bytes);
            return  Strings.equals(base64,signature);
        } catch (Exception e) {
            throw new RuntimeException("Verify signature error", e);
        }
    }
419702
private function validateSignature(): void
    {
        $signature = '';

        try {
            $signature = $this->encode->signature(
                $this->encode->decode($this->getHeader()),
                $this->encode->decode($this->getPayload()),
                $this->jwt->getSecret()
            );
        } catch (\Throwable $e) {
            throw new ValidateException('Token could not be parsed.', 2);
        }

        if (!$this->validate->signature($signature, $this->getSignature())) {
            throw new ValidateException('Signature is invalid.', 3);
        }
    }
477369
function () {
                try {
                    authHandler.sign(authInterface, context.item.request, function (err) {
                        // handle all types of errors in one place, see catch block
                        if (err) { throw err; }

                        done();
                    });
                }
                catch (err) {
                    // handles synchronous and asynchronous errors in auth.sign
                    run.triggers.console(context.coords,
                        'warn',
                        'runtime~' + authType + '.auth: could not sign the request: ' + (err.message || err),
                        err
                    );

                    // swallow the error, we've warned the user
                    done();
                }
            }
355096
private function verifySignature(Object\JWSInterface $jws, Object\JWKSetInterface $jwk_set, Object\SignatureInterface $signature, $detached_payload = null)
    {
        $input = $this->getInputToVerify($jws, $signature, $detached_payload);
        foreach ($jwk_set->getKeys() as $jwk) {
            $algorithm = $this->getAlgorithm($signature);

            try {
                $this->checkKeyUsage($jwk, 'verification');
                $this->checkKeyAlgorithm($jwk, $algorithm->getAlgorithmName());
                if (true === $algorithm->verify($jwk, $input, $signature->getSignature())) {
                    return true;
                }
            } catch (\Exception $e) {
                //We do nothing, we continue with other keys
                continue;
            }
        }

        return false;
    }
937583
public void validateWsFederationAuthenticationRequest(final RequestContext context) {
        val service = wsFederationCookieManager.retrieve(context);
        LOGGER.debug("Retrieved service [{}] from the session cookie", service);

        val request = WebUtils.getHttpServletRequestFromExternalWebflowContext(context);
        val wResult = request.getParameter(WRESULT);
        LOGGER.debug("Parameter [{}] received: [{}]", WRESULT, wResult);
        if (StringUtils.isBlank(wResult)) {
            LOGGER.error("No [{}] parameter is found", WRESULT);
            throw new IllegalArgumentException("Missing parameter " + WRESULT);
        }
        LOGGER.debug("Attempting to create an assertion from the token parameter");
        val rsToken = wsFederationHelper.getRequestSecurityTokenFromResult(wResult);
        val assertion = wsFederationHelper.buildAndVerifyAssertion(rsToken, configurations);
        if (assertion == null) {
            LOGGER.error("Could not validate assertion via parsing the token from [{}]", WRESULT);
            throw new IllegalArgumentException("Could not validate assertion via the provided token");
        }
        LOGGER.debug("Attempting to validate the signature on the assertion");
        if (!wsFederationHelper.validateSignature(assertion)) {
            val msg = "WS Requested Security Token is blank or the signature is not valid.";
            LOGGER.error(msg);
            throw new IllegalArgumentException(msg);
        }
        buildCredentialsFromAssertion(context, assertion, service);
    }
809616
public function bingVerifAction()
    {
        if ( !$this->getConfigResolver()->hasParameter( 'bing_verification', 'nova_ezseo' ) )
        {
            throw new NotFoundHttpException( "Bing Verification Key not found" );
        }

        $key = $this->getConfigResolver()->getParameter( 'bing_verification', 'nova_ezseo' );

        $xml = new DOMDocument("1.0", "UTF-8");
        $xml->formatOutput = true;

        $root = $xml->createElement("users");
        $root->appendChild($xml->createElement("user", $key));
        $xml->appendChild($root);

        $response = new Response($xml->saveXML());
        $response->setSharedMaxAge( 24 * 3600 );
        $response->headers->set("Content-Type", "text/xml");
        return $response;
    }
852043
protected function validateRequest()
    {
        //Twilio requires that all POST data be sorted alpha to validate.
        $data = $_POST;
        ksort($data);

        // append the data array to the url string, with no delimiters
        $url = $this->url;
        foreach ($data as $key => $value) {
            $url = $url.$key.$value;
        }

        //Encode the request string
        $hmac = hash_hmac('sha1', $url, $this->authToken, true);

        //Verify it against the given Twilio key
        if (base64_encode($hmac) != $_SERVER['HTTP_X_TWILIO_SIGNATURE']) {
            throw new \InvalidArgumentException('This request was not able to verify it came from Twilio.');
        }
    }
831112
public function triggerHook()
    {
        $hookUrl = $this->getLink('#hook');
        $options = [];

        // The API needs us to send an empty JSON object.
        $options['json'] = new \stdClass();

        // Switch off authentication for this request (none is required).
        $options['auth'] = null;

        $this->sendRequest($hookUrl, 'post', $options);
    }