Authenticate an HTTP response with a pre-shared key.

@param ResponseInterface $response
@param SharedAuthenticationKey $key
@return ResponseInterface
353703
public function authenticateResponseWithSharedKey(
        ResponseInterface $response,
        SharedAuthenticationKey $key
    ): ResponseInterface {
        $mac = \ParagonIE_Sodium_Compat::crypto_auth(
            (string) $response->getBody(),
            $key->getString(true)
        );
        return $response->withAddedHeader(
            self::HEADER_AUTH_NAME,
            Base64UrlSafe::encode($mac)
        );
    }
1227915
public function decryptJsonRequestWithSharedKey(
        RequestInterface $request,
        SharedEncryptionKey $key
    ): array {
        $decrypted = $this->decryptRequestWithSharedKey(
            $request,
            $key
        );

        /** @var array|bool $array */
        $array = \json_decode(
            (string) $decrypted->getBody(),
            true
        );
        if (!\is_array($array)) {
            throw new InvalidMessageException('Could not decode JSON');
        }
        return $array;
    }
22595
public function googleVerifAction( $key )
    {
        if ( $this->getConfigResolver()->getParameter( 'google_verification', 'nova_ezseo' ) != $key )
        {
            throw new NotFoundHttpException( "Google Verification Key not found" );
        }
        $response = new Response();
        $response->setSharedMaxAge( 24 * 3600 );
        $response->setContent( "google-site-verification: google{$key}.html" );
        return $response;
    }
1338197
@Override
    protected int authenticated(final Request request, final Response response)
    {
        try
        {
            final CookieSetting credentialsCookie = this.getCredentialsCookie(request, response);
            credentialsCookie.setValue(this.formatCredentials(request.getChallengeResponse()));
            credentialsCookie.setMaxAge(this.getMaxCookieAge());
        }
        catch(final GeneralSecurityException e)
        {
            this.log.error("Could not format credentials cookie", e);
        }
        
        // log.info("calling super.authenticated");
        // return super.authenticated(request, response);
        
        // Modified copy of Authenticator.authenticated
        if(this.log.isDebugEnabled())
        {
            this.log.debug("The authentication succeeded for the identifer \"{}\" using the {} scheme.", request
                    .getChallengeResponse().getIdentifier(), request.getChallengeResponse().getScheme());
        }
        
        // Update the client info accordingly
        if(request.getClientInfo() != null)
        {
            request.getClientInfo().setAuthenticated(true);
        }
        
        // Clear previous challenge requests
        response.getChallengeRequests().clear();
        
        // Add the roles for the authenticated subject
        if(this.getEnroler() != null)
        {
            this.getEnroler().enrole(request.getClientInfo());
        }
        
        // Return STOP here works for login but not for subsequent requests that expect a response
        // return STOP;
        return Filter.CONTINUE;
    }
522268
protected function addCookieToResponse(Response $response, SessionInterface $session)
	{
		$s = $session;

		if ($this->sessionIsPersistent($c = $this->manager->getSessionConfig()))
		{
			$secure = array_get($c, 'secure', false);

			$response->headers->setCookie(new Cookie(
				$s->getName(), $s->getId(), $this->getCookieLifetime(), $c['path'], $c['domain'], $secure
			));
		}
	}
654211
public function collect(Request $request, Response $response, \Exception $exception = null)
    {
        if (null === $this->getSecurityContext()) {
            return true;
        }

        $key = \sprintf('%s.anonymous', $this->getStatsDataKey());
        try {
            if ($this->getSecurityContext()->isGranted('IS_AUTHENTICATED_FULLY')) {
                $key = \sprintf('%s.logged', $this->getStatsDataKey());
            }
        } catch (AuthenticationCredentialsNotFoundException $exception) {
            //do nothing
        }
        $statData = $this->getStatsdDataFactory()->increment($key);
        $this->addStatsData($statData);

        return true;
    }
265469
public function checkFieldKey(ServerRequest $request, Response $response): Response
    {
        $queryParams = $request->getQueryParams();
        $fieldKey = $queryParams['key'];
        $table = 'tt_content';
        if (isset($queryParams['table'])) {
            $table = $queryParams['table'];
        }

        $objectManager = GeneralUtility::makeInstance(ObjectManager::class);
        $storageRepository = $objectManager->get(StorageRepository::class);

        // check if fieldKey is available for this table
        $isAvailable = true;
        if ($storageRepository->loadField($table, $fieldKey)) {
            $isAvailable = false;
        }

        return new JsonResponse(['isAvailable' => $isAvailable]);
    }
1328119
protected function getExistingIdentity( UserResponseInterface $response )
    {
        $repo = $this->om->getRepository( $this->userIdentityClass );   // wrong class
        return $repo->findOneBy( array(
            'identifier' => $response->getUsername(),
            'type' => $response->getResourceOwner()->getName(),
        ));
    }
319060
protected function encrypt(Response $response)
	{
		foreach ($response->headers->getCookies() as $key => $c)
		{
			$encrypted = $this->encrypter->encrypt($c->getValue());

			$response->headers->setCookie($this->duplicate($c, $encrypted));
		}

		return $response;
	}
1312130
public function verifySymmetricAuthenticatedStringRequest(
        RequestInterface $request,
        SharedAuthenticationKey $key
    ): string {
        $verified = $this->verifySymmetricAuthenticatedRequest($request, $key);
        return (string) $verified->getBody();
    }
565230
protected function cacheResponse(RequestInterface $request, ResponseInterface $response)
    {
        $cacheItem = $this->createCacheItem($this->createKeyFromRequest($request));
        $value = $response->getBody()->__toString();
        $cacheItem->set($value);

        $this
            ->getCacheItemPool()
            ->save($cacheItem);
    }
163340
private function handleRedirect(ResponseInterface $response): ResponseInterface
    {
        if ($this->debugbar->isDataPersisted() || session_status() === PHP_SESSION_ACTIVE) {
            $this->debugbar->stackData();
        }

        return $response;
    }
1059949
protected function authenticate($key, $secret) {
		$token = $this->cache->get('Twitter_Application_Bearer_Token');
		if ($token === FALSE) {
			$bearerTokenCredentials = base64_encode(urlencode($key) . ':' . urlencode($secret));

			$uri = new Uri('https://api.twitter.com/oauth2/token');
			$httpRequest = Request::create($uri, 'POST');
			$httpRequest->setContent(http_build_query(array('grant_type' => 'client_credentials')));
			$httpRequest->setHeader('Authorization', 'Basic ' . $bearerTokenCredentials);
			$httpRequest->setHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');

			$response = $this->requestEngine->sendRequest($httpRequest);
			$authenticationReponseBody = json_decode($response->getContent(), TRUE);
			if (!isset($authenticationReponseBody['token_type']) || $authenticationReponseBody['token_type'] !== 'bearer' || !isset($authenticationReponseBody['access_token'])) {
				throw new \Exception('Invalid authentication answer! Your application could not authenticate with Twitter.', 1424698337);
			}

			$token = $authenticationReponseBody['access_token'];
			$this->cache->set('Twitter_Application_Bearer_Token', $token);
		}

		return $token;
	}
527849
protected function withEncryptedCookies(ResponseInterface $response): ResponseInterface
    {
        //$cookiesManager = new CookiesManager();
        //$cookies = CookiesManager::parseHeaders($response->getHeader('Set-Cookie'));

        $cookies = CookiesManager::parseSetCookieHeader($response->getHeader('Set-Cookie'));

        // remove all the cookies
        $response = $response->withoutHeader('Set-Cookie');

        //$header = [];
        foreach ($cookies as $name => $cookie) {
            if (! in_array($name, $this->bypassed)) {
                $cookie['value'] = $this->encrypt($cookie['value']);
            }

            //$cookiesManager->set($name, $value);
            // add again all the cookies (and some are now encrypted)
            $response = $response->withAddedHeader('Set-Cookie', CookiesManager::toHeader($name, $cookie));
        }

        return $response;
    }
544842
public function keyCheck($apiKey = null, $url = null)
    {
        if ($apiKey === null || $url === null) {
            throw new InvalidArgumentException('Both apiKey and site URL cannot be null');
        }

        return $this->connection->keyCheck($apiKey, $url);
    }
26347
public function authenticateUserAndHandleSuccess(UserInterface $user, Request $request, AuthenticatorInterface $authenticator, string $providerKey): ?Response
    {
        // create an authenticated token for the User
        $token = $authenticator->createAuthenticatedToken($user, $providerKey);
        // authenticate this in the system
        $this->authenticateWithToken($token, $request, $providerKey);

        // return the success metric
        return $this->handleAuthenticationSuccess($token, $request, $authenticator, $providerKey);
    }
101550
public function createAuthenticatedToken(UserInterface $user, $providerKey)
    {
        $preAuthToken = $this->preAuthenticationTokenStorage->getToken();

        if (null === $preAuthToken) {
            throw new \RuntimeException('Unable to return an authenticated token since there is no pre authentication token.');
        }

        $authToken = new JWTUserToken($user->getRoles(), $user, $preAuthToken->getCredentials(), $providerKey);

        if ($this->dispatcher instanceof ContractsEventDispatcherInterface) {
            $this->dispatcher->dispatch(new JWTAuthenticatedEvent($preAuthToken->getPayload(), $authToken), Events::JWT_AUTHENTICATED);
        } else {
            $this->dispatcher->dispatch(Events::JWT_AUTHENTICATED, new JWTAuthenticatedEvent($preAuthToken->getPayload(), $authToken));
        }

        $this->preAuthenticationTokenStorage->setToken(null);

        return $authToken;
    }