Inject token to response object.

@param ResponseInterface $response the response
@param string $tokenValue token value

@throws RuntimeException

@return ResponseInterface the response
961699
private function injectTokenToResponse(ResponseInterface $response, string $tokenValue): ResponseInterface
    {
        // Check if response is html
        $contentTypes = $response->getHeader('content-type');
        $contentType = reset($contentTypes) ?: '';
        if (strpos($contentType, 'text/html') === false) {
            return $response;
        }

        $content = $response->getBody()->__toString();

        if ($this->protectForms) {
            $content = $this->injectFormHiddenFieldToResponse($content, $tokenValue);
        }

        if ($this->protectJqueryAjax) {
            $content = $this->injectJqueryToResponse($content, $tokenValue);
        }

        return $response->withBody($this->streamFactory->createStream($content));
    }
140441
protected function createRedirectTokenResponse(
        TokenInterface $token,
        int $tokenExpiresIn,
        string $state = null
    ): ResponseInterface {
        $this->logDebug('Sending token as redirect response.');

        $scopeList  = $token->isScopeModified() === false || empty($token->getScopeIdentifiers()) === true ?
            null : $token->getScopeList();

        // for access token format @link https://tools.ietf.org/html/rfc6749#section-5.1
        $parameters = $this->filterNulls([
            'access_token' => $token->getValue(),
            'token_type'   => $token->getType(),
            'expires_in'   => $tokenExpiresIn,
            'scope'        => $scopeList,
            'state'        => $state,
        ]);

        $fragment = $this->encodeAsXWwwFormUrlencoded($parameters);

        $response = new RedirectResponse((new Uri($token->getRedirectUriString()))->withFragment($fragment));

        return $response;
    }
245309
public function renewToken(?Token $token) : Token
    {
        if ($token === null) {
            throw new NullValueException("Token cannot be null");
        }

        $token->updateExisting([
            'token' => $this->generateToken($this->config->get('app.key')),
        ]);

        $this->fireUpdatedEvent($token->user, $token);

        return $token;
    }
41423
public function setTokenInputName($tokenInputName = null)
    {
        if ($tokenInputName === null) {
            $tokenInputName = 'form_key';
        }

        $this->setData('token_input_name', $tokenInputName);
        return $this;
    }
674236
final public function loginSuccess(Request $request, Response $response, TokenInterface $token)
    {
        // Make sure any old remember-me cookies are cancelled
        $this->cancelCookie($request);

        if (!$token->getUser() instanceof UserInterface) {
            if (null !== $this->logger) {
                $this->logger->debug('Remember-me ignores token since it does not contain a UserInterface implementation.');
            }

            return;
        }

        if (!$this->isRememberMeRequested($request)) {
            if (null !== $this->logger) {
                $this->logger->debug('Remember-me was not requested.');
            }

            return;
        }

        if (null !== $this->logger) {
            $this->logger->debug('Remember-me was requested; setting cookie.');
        }

        // Remove attribute from request that sets a NULL cookie.
        // It was set by $this->cancelCookie()
        // (cancelCookie does other things too for some RememberMeServices
        // so we should still call it at the start of this method)
        $request->attributes->remove(self::COOKIE_ATTR_NAME);

        $this->onLoginSuccess($request, $response, $token);
    }
935478
public function parse(Token $token): ValueInterface
    {
        parent::parse($token);

        $value = $token->getValue();
        try {
            $elements = substr($value, 1, strlen($value) - 2);

            return new ArrayValue($this->parseElements($this->parser, $elements));
        } catch (\TypeError $error) {
            throw ExpressionLanguageExceptionFactory::createForUnparsableToken($token, 0, $error);
        }
    }
894687
public function parse(Token $token): ParameterValue
    {
        $value = $token->getValue();
        try {
            $paramKey = substr($value, 2, strlen($value) - 4);

            return new ParameterValue($paramKey);
        } catch (\TypeError $error) {
            throw ExpressionLanguageExceptionFactory::createForUnparsableToken($token, 0, $error);
        }
    }
717661
private function processResponse(ResponseInterface $response)
    {
        if (200 !== $response->getStatusCode()) {
            throw new \RuntimeException('Query to the API server did not result in an appropriate response code');
        }

        $body = guzzle_json_decode((string) $response->getBody(), true);

        if ('OK' !== $body['error']) {
            throw new \RuntimeException('Query to the API server did not result in an appropriate response code');
        }

        return $body;
    }
827616
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
    {
        try {
            $event = new ApiAuthenticateEvent();

            if (null !== $token->getCredentials()) {
                $event->setUserName($token->getUsername());
                $event->setPassword($token->getCredentials());
                $this->dispatcher->dispatch(ApiAuthenticationEvents::AUTHENTICATE, $event);
            } elseif ($token->getUser() instanceof User) {
                //if we have no password then only way to authenticate is by api key
                $event->setApiKey($token->getUser()->getApiKey());
                $this->dispatcher->dispatch(ApiAuthenticationEvents::API_KEY_AUTHENTICATE, $event);
            }

            $user = $userProvider->loadUserByUsername($token->getUsername());
        } catch (UsernameNotFoundException $e) {
            throw new AuthenticationException($e->getMessage());
        }

        return new UsernamePasswordToken(
            $user,
            $user->getPassword(),
            $providerKey,
            $user->getRoles()
        );
    }
473158
public function createToken(UserInterface $user, string $operator = null): TokenInterface
    {
        return $this->getOperator($operator ?? $this->config->defaultOperator())->createToken($user);
    }
980987
public function authenticateWithToken(TokenInterface $token, Request $request, string $providerKey = null)
    {
        $this->migrateSession($request, $token, $providerKey);
        $this->tokenStorage->setToken($token);

        if (null !== $this->dispatcher) {
            $loginEvent = new InteractiveLoginEvent($request, $token);
            $this->dispatcher->dispatch($loginEvent, SecurityEvents::INTERACTIVE_LOGIN);
        }
    }
1329026
public function setToken($token, $tokenValue, $append = false, $first = false)
    {
        return $this->setTokenValues($token, array($tokenValue), $append, $first);
    }
1080186
public function endToken(TokenInterface $token)
    {
        $token->getSourceLocation()->setOffsetLength(
            $this->reader->getOffset() - $token->getSourceLocation()->getOffset()
        );

        return $token;
    }
748689
public function readByValue(string $tokenValue, int $expirationInSeconds): ?TokenInterface
    {
        $schema = $this->getDatabaseSchema();
        return $this->readEnabledTokenByColumnWithExpirationCheck(
            $tokenValue,
            $schema->getTokensValueColumn(),
            $expirationInSeconds,
            $schema->getTokensValueCreatedAtColumn()
        );
    }
269543
public function setToken($tokenId, CsrfToken $token) {
		
		if(!trim((string) $tokenId)) {
			throw new \InvalidArgumentException('Invalid token id.');
		}
		
		$this->sessionDataBag->set(
			$this->namespace . '/' . $tokenId,
			$token
		);
	}
394942
public function isTokenEqualToOrPrecededBy($tokenPosition, $stringValue)
    {
        return $this->isTokenEqualTo($tokenPosition, $stringValue)
            || $this->isTokenPrecededBy($tokenPosition, $stringValue);
    }
591590
public function executeRequest($method, $url, $token, $body = null)
    {
        $options = [];
        if ($body) {
            $options['body'] = json_encode($body);
            $options['headers']['Content-Type'] = 'application/json';
        }

        $request = $this->getAuthenticatedRequest($method, $this->apiDomain.'/'.$this->version.$url, $token, $options);

        return $this->getParsedResponse($request);
    }