public static function getRealUri(ServerRequestInterface $request) { $uri = $request->getUri(); if ($request->hasHeader(self::PROTO_HEADER_HEROKU)) { $uri = $uri->withScheme($request->getHeader(self::PROTO_HEADER_HEROKU)[0]); } if ($request->hasHeader(self::PORT_HEADER_HEROKU)) { $uri = $uri->withPort(intval($request->getHeader(self::PORT_HEADER_HEROKU)[0])); } return $uri; }
/** * @param \Psr\Http\Message\ServerRequestInterface $request * @return \Psr\Http\Message\ResponseInterface * @throws \Wandu\Http\Exception\BadRequestException */ function back(ServerRequestInterface $request) { if ($request->hasHeader('referer')) { return redirect($request->getHeader('referer')); } throw new BadRequestException(); }
public function __invoke(Request $request) { /** Check for token on header */ if (isset($this->options['header'])) { if ($request->hasHeader($this->options['header'])) { $header = $request->getHeader($this->options['header'])[0]; if (preg_match($this->options['regex'], $header, $matches)) { return $matches[1]; } } } /** If nothing on header, try query parameters */ if (isset($this->options['parameter'])) { if (!empty($request->getQueryParams()[$this->options['parameter']])) { return $request->getQueryParams()[$this->options['parameter']]; } } /** If nothing on parameters, try cookies */ if (isset($this->options['cookie'])) { $cookie_params = $request->getCookieParams(); if (!empty($cookie_params[$this->options["cookie"]])) { return $cookie_params[$this->options["cookie"]]; } } /** If nothing until now, check argument as last try */ if (isset($this->options['argument'])) { if ($route = $request->getAttribute('route')) { $argument = $route->getArgument($this->options['argument']); if (!empty($argument)) { return $argument; } } } throw new TokenNotFoundException('Token not found'); }
/** * {@inheritdoc} */ public function validateAuthorization(ServerRequestInterface $request) { if ($request->hasHeader('authorization') === false) { throw OAuthServerException::accessDenied('Missing "Authorization" header'); } $header = $request->getHeader('authorization'); $jwt = trim(preg_replace('/^(?:\\s+)?Bearer\\s/', '', $header[0])); try { // Attempt to parse and validate the JWT $token = (new Parser())->parse($jwt); if ($token->verify(new Sha256(), $this->publicKey->getKeyPath()) === false) { throw OAuthServerException::accessDenied('Access token could not be verified'); } // Ensure access token hasn't expired $data = new ValidationData(); $data->setCurrentTime(time()); if ($token->validate($data) === false) { throw OAuthServerException::accessDenied('Access token is invalid'); } // Check if token has been revoked if ($this->accessTokenRepository->isAccessTokenRevoked($token->getClaim('jti'))) { throw OAuthServerException::accessDenied('Access token has been revoked'); } // Return the request with additional attributes return $request->withAttribute('oauth_access_token_id', $token->getClaim('jti'))->withAttribute('oauth_client_id', $token->getClaim('aud'))->withAttribute('oauth_user_id', $token->getClaim('sub'))->withAttribute('oauth_scopes', $token->getClaim('scopes')); } catch (\InvalidArgumentException $exception) { // JWT couldn't be parsed so return the request as is throw OAuthServerException::accessDenied($exception->getMessage()); } catch (\RuntimeException $exception) { //JWR couldn't be parsed so return the request as is throw OAuthServerException::accessDenied('Error while decoding to JSON'); } }
/** * Invoking the middleware * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * @return ResponseInterface $response * @throws InternalServerError * @throws UnsupportedMediaType */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { // Make sure we have deserializers if (!isset($this->container['contentTypes'])) { throw new InternalServerError('No serializers seems to be configured'); } // Make sure we have a content type header to work with if ($request->hasHeader('Content-Type')) { // Get the content of the header $header = $request->getHeaderLine('Content-Type'); // Make sure the header value isn't empty if (!empty($header)) { // Get priorities $supported = $this->container['contentTypes']; // Remove included parts that aren't part of the RFC $header = preg_replace('/(;[a-z]*=[a-z0-9\\-]*)/i', '', $header); // Replace the original header value $request = $request->withHeader('Content-Type', $header); // Check if the content type is supported if (!in_array($header, $supported)) { // The content type isn't supported throw new UnsupportedMediaType('Can not handle the supplied content type. Supported types are ' . implode(', ', $supported)); } } } // Call next middleware return $next($request, $response, $next); }
/** * {@inheritdoc} */ public function __invoke(Request $request, Response $response, callable $out = null) { if ($request->getMethod() === 'POST' && $request->hasHeader(self::HEADER_NAME)) { $fakeMethod = $request->getHeaderLine(self::HEADER_NAME); $request = $request->withMethod(strtoupper($fakeMethod)); } return $out ? $out($request, $response) : $response; }
/** * @param \Psr\Http\Message\ServerRequestInterface $request * * @return string * @throws \livetyping\hermitage\app\exceptions\UnauthorizedException */ protected function getSignatureFromRequest(Request $request) : string { if (!$request->hasHeader(self::HEADER_AUTHENTICATE_SIGNATURE)) { throw new UnauthorizedException('Signature is required.'); } $signature = current($request->getHeader(self::HEADER_AUTHENTICATE_SIGNATURE)); return $signature; }
/** * Process an incoming request and/or response. * * Accepts a server-side request and a response instance, and does * something with them. * * If the response is not complete and/or further processing would not * interfere with the work done in the middleware, or if the middleware * wants to delegate to another process, it can use the `$out` callable * if present. * * If the middleware does not return a value, execution of the current * request is considered complete, and the response instance provided will * be considered the response to return. * * Alternately, the middleware may return a response instance. * * Often, middleware will `return $out();`, with the assumption that a * later middleware will return a response. * * @param Request $request * @param Response $response * @param null|callable $out * @return null|Response */ public function __invoke(Request $request, Response $response, callable $out = null) { if (!$request->hasHeader('Accept-Language')) { return $out($request, $response); } $locale = $request->getHeaderLine('Accept-Language'); $this->translator->setLocale($this->normalizeLocale($locale)); return $out($request, $response); }
public function enrichRequestWithParsedBody(ServerRequestInterface $request) { if ($request->hasHeader(HeaderName::CONTENT_TYPE) && $request->getHeaderLine(HeaderName::CONTENT_TYPE) === 'application/json') { $parsedBody = $this->serializer->deserialize($request->getBody()->__toString(), 'array', 'json'); return $request->withParsedBody($parsedBody); } else { return $request->withParsedBody([]); } }
public function __invoke(Request $request, Response $response, callable $out = null) { if (!$request->hasHeader('authorization')) { return $response->withStatus(401); } if (!$this->isValid($request)) { } return $out($request, $response); }
public function __invoke(Request $request, Response $response, callable $next) : Response { $parent = $request->getOriginalRequest(); $parentUrl = str_replace('/thank-you', '', (string) $parent->getUri()); if (!$request->hasHeader('Referer') || !preg_match('#^' . $parentUrl . '#', $request->getHeaderLine('Referer'))) { return $response->withStatus(302)->withHeader('Location', $parentUrl); } return new HtmlResponse($this->template->render('contact::thankyou', [])); }
/** * @param ServerRequestInterface $request * * @return array */ private function getHeadersFromRequest(ServerRequestInterface $request) { $headerNames = []; foreach ($this->service->getOverrideHeaders() as $headerName) { if ($request->hasHeader($headerName)) { $headerNames[$headerName] = $request->getHeaderLine($headerName); } } return $headerNames; }
/** * Fetch token from request. * * @param ServerRequestInterface $request * @return string */ protected function fetchToken(ServerRequestInterface $request) { if ($request->hasHeader(self::HEADER)) { return (string) $request->getHeaderLine(self::HEADER); } $data = $request->getParsedBody(); if (is_array($data) && isset($data[self::PARAMETER])) { if (is_string($data[self::PARAMETER])) { return (string) $data[self::PARAMETER]; } } return ''; }
/** * Check if the provided origin is allowed to * access the api * * @return bool */ protected function checkOrigin() { // Check if we allow all "*" if ($this->options['allowedOrigins'] === true) { return true; } // Make sure the origin header is set and that the value (domain) is // in the allowed origins list. if ($this->request->hasHeader('origin') && in_array($this->request->getHeaderLine('origin'), $this->options['allowedOrigins'])) { return true; } return false; }
private function isAcceptableServerRequest(ServerRequestInterface $request) : bool { if (!$request->hasHeader("Accept-encoding")) { return false; } $accept = $request->getHeaderLine("Accept-encoding"); if (strpos($accept, '*') !== false) { return true; } if (strpos($accept, 'gzip') !== false) { return true; } return false; }
/** * {@inheritdoc} * * @throws \RuntimeException */ public function isExcluded(ServerRequestInterface $request) { if (!count($this->headers)) { throw new \RuntimeException('No headers defined in header excluder'); } foreach ($this->headers as $header => $value) { if ($value === null && $request->hasHeader($header)) { return true; } elseif ($value !== null && (trim($value) === $request->getHeaderLine($header) || @preg_match(trim($value), $request->getHeaderLine($header)))) { return true; } } return false; }
/** * Extract the token either from Authorization header or query params * * @param ServerRequestInterface $request * @return string|null */ private function extractAccessToken(ServerRequestInterface $request) { // The preferred way is using Authorization header if ($request->hasHeader('Authorization')) { // Header value is expected to be "Bearer xxx" $parts = explode(' ', $request->getHeaderLine('Authorization')); if (count($parts) < 2) { return null; } return end($parts); } // Default back to authorization in query param $queryParams = $request->getQueryParams(); return $queryParams['access_token'] ?? null; }
public function __invoke(Request $request, Response $response, callable $out = null) { //Sin header no pasas if (!$request->hasHeader('authorization')) { $response->getBody()->write('WTF! Unauthorized'); return $response->withStatus(401); } //Autenticacion valida? if (!$this->isValid($request)) { $response->getBody()->write('Invalid token!'); return $response->withStatus('403'); } //seguimos con la suguiente capa return $out($request, $response); }
/** * Build CorsRequest from PSR-7 ServerRequest object * * @param Psr\Http\Message\ServerRequestInterface $request * @return PhpNexus\Cors\CorsRequest */ protected function buildCorsRequest(ServerRequestInterface $request) { // Create CorsRequest and set method $corsRequest = (new CorsRequest())->setMethod($request->getMethod()); // Set Origin if header exists if ($request->hasHeader('Origin')) { $corsRequest->setOrigin($request->getHeader('Origin')[0]); } // Set access control request method if header exists if ($request->hasHeader('Access-Control-Request-Method')) { $corsRequest->setAccessControlRequestMethod($request->getHeader('Access-Control-Request-Method')[0]); } // Set access control request headers if header exists if ($request->hasHeader('Access-Control-Request-Headers')) { /** Not sure if this is a bug in the Slim implementation of PSR-7, but it doesn't seem to separate headers properly */ $accessControlRequestHeaders = $request->getHeader('Access-Control-Request-Headers'); // If only one array element; explode by comma and space if (count($accessControlRequestHeaders) === 1) { $accessControlRequestHeaders = explode(', ', $accessControlRequestHeaders[0]); } $corsRequest->setAccessControlRequestHeaders($accessControlRequestHeaders); } return $corsRequest; }
private function generateResponseLog(Request $request, Response $response) { if ($this->options['full']) { return ResponseSerializer::toString($response); } $reasonPhrase = $response->getReasonPhrase(); $msg = sprintf("%s %s", $response->getStatusCode(), $reasonPhrase ? $reasonPhrase : ''); if ($response->hasHeader('X-Request-Id')) { $msg .= ' RequestId: ' . $response->getHeader('X-Request-Id')[0]; } elseif ($request->hasHeader('X-Request-Id')) { $msg .= ' RequestId: ' . $request->getHeader('X-Request-Id')[0]; } if ($response->hasHeader('X-Response-Time')) { $msg .= ' ResponseTime: ' . $response->getHeader('X-Response-Time')[0]; } return $msg; }
/** * Process an incoming request and/or response. * * Accepts a server-side request and a response instance, and does * something with them. * * If the response is not complete and/or further processing would not * interfere with the work done in the middleware, or if the middleware * wants to delegate to another process, it can use the `$out` callable * if present. * * If the middleware does not return a value, execution of the current * request is considered complete, and the response instance provided will * be considered the response to return. * * Alternately, the middleware may return a response instance. * * Often, middleware will `return $out();`, with the assumption that a * later middleware will return a response. * * @param Request $request * @param Response $response * @param null|callable $out * * @return null|Response */ public function __invoke(Request $request, Response $response, callable $out = null) { $authHeader = $request->hasHeader('Authorization') ? $request->getHeaderLine('Authorization') : null; if (empty($authHeader)) { return $this->unauthorizedResponse($response); } if (false === strpos($authHeader, 'token')) { return $this->unauthorizedResponse($response); } list(, $token) = explode(' ', $authHeader); if (!isset($token)) { return $this->unauthorizedResponse($response); } if (!$this->authService->authorize($token)) { return $this->forbiddenResponse($response); } return $out($request, $response); }
/** * Invoking the middleware * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * @return ResponseInterface $response * @throws InternalServerError * @throws NotAcceptable */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { // Make sure we have serializers if (!isset($this->container['acceptTypes'])) { throw new InternalServerError('No serializers seems to be registered'); } // Get priorities $supported = $this->container['acceptTypes']; // Prepare charset $charset = $this->prepareCharsetHeaderString(); // Make sure we have what we need to do the negotiation if ($request->hasHeader('Accept')) { // Get header $accept = $request->getHeaderLine('Accept'); // Negotiate $best = $this->getBestFormat($accept, $supported); // If an Accept header field is present, and if the server cannot send a response // which is acceptable according to the combined Accept field value, then the server // SHOULD return a 406 (not acceptable) response. if ($best === null) { // We must set the mime type before throwing the exception so that the correct serializer // is triggered to serialize the error message. Both on the request and response. $this->container['latestRequest'] = $request->withAttribute('Accept', $supported[0]); $this->container['latestResponse'] = $response->withHeader('Content-Type', $supported[0] . $charset); throw new NotAcceptable('Can not send a response which is acceptable according to the Accept header. ' . 'Supported mime types are: ' . implode(', ', $supported)); } } else { // If no Accept header field is present, then it is assumed that the client accepts all media types. $best = $this->acceptsAnything(1, $supported); } // Save result $request = $request->withAttribute('Accept', $best['value']); // Set response content type header $response = $response->withHeader('Content-Type', $best['value'] . $charset); // Set extra params if (isset($best['parameters'])) { // Set parameters array as attribute $request = $request->withAttribute('Accept-Parameters', $best['parameters']); } // Call next middleware return $next($request, $response, $next); }
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { if (false === $request->hasHeader('Authorization')) { if (false === $this->allRequests) { return $next($request, $response); } return $this->invalidResponse; } $token = $request->getHeaderLine('Authorization'); if (false === strpos($token, 'Bearer ')) { return $this->invalidResponse; } $token = substr($token, 7); /** @var SimpleJWS $jws */ $jws = SimpleJWS::load($token, false); if (false === $jws->isValid($this->publicKey, $this->encoder)) { return $this->invalidResponse; } return $next($request->withAttribute('jwt', $jws->getPayload()), $response); }
/** * {@inheritdoc} */ public function initialize(ServerRequestInterface $request) { if (!$request->hasHeader('Authorization')) { return null; } $authorization = $request->getHeaderLine('Authorization'); if (empty($authorization) || substr($authorization, 0, 6) !== 'Bearer') { return null; } $token_id = trim(substr($authorization, 7)); if ($token_id === null || $token_id === '') { throw new InvalidTokenException(); } if ($token = $this->token_repository->getById($token_id)) { if ($user = $token->getAuthenticatedUser($this->user_repository)) { $this->token_repository->recordUsageByToken($token); return new AuthenticationTransport($this, $user, $token); } } throw new InvalidTokenException(); }
/** * Handle the middleware pipeline call * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * @return mixed * @throws MethodNotAllowed */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { // Check if the override header is set if ($request->hasHeader('X-Http-Method-Override')) { // Get the original request method $method = $request->getMethod(); // Get the override method $override = strtoupper($request->getHeaderLine('X-Http-Method-Override')); // Check so the override method are allowed based on the original request method if ($method === 'GET' && in_array($override, $this->getOverride) || $method === 'POST' && in_array($override, $this->postOverride)) { // Save current method as attribute $request = $request->withAttribute('originalRequestMethod', $method); // Set the override method as request method $request = $request->withMethod($override); } else { throw new MethodNotAllowed('The override method ' . $override . ' are not allowed to override the original ' . $method . ' request method.'); } } // Call next middleware return $next($request, $response, $next); }
/** * {@inheritdoc} */ public function validateAuthorization(ServerRequestInterface $request) { if ($request->hasHeader('authorization') === false) { throw OAuthServerException::accessDenied('Missing "Authorization" header'); } $header = $request->getHeader('authorization'); $accessTokenId = trim($header[0]); try { $accessTokenEntity = $this->accessTokenRepository->findAccessToken($accessTokenId); // Check if token has been revoked if (is_null($accessTokenEntity)) { throw OAuthServerException::accessDenied('Access token has been revoked'); } // Ensure access token hasn't expired if ($accessTokenEntity->getExpiryDateTime()->lt(Carbon::now())) { throw OAuthServerException::accessDenied('Access token is invalid'); } // Return the request with additional attributes return $request->withAttribute('oauth_access_token_id', $accessTokenEntity->getIdentifier())->withAttribute('oauth_client_id', $accessTokenEntity->getClient()->getIdentifier())->withAttribute('oauth_user_id', $accessTokenEntity->getUserIdentifier())->withAttribute('oauth_scopes', $accessTokenEntity->getScopes()); } catch (\InvalidArgumentException $exception) { // JWT couldn't be parsed so return the request as is throw OAuthServerException::accessDenied($exception->getMessage()); } }
/** * {@inheritdoc} */ public function hasHeader($name) { return $this->wrapped->hasHeader($name); }
/** * {@inheritDoc} */ public function hasHeader($name) { return $this->psrRequest->hasHeader($name); }
/** * Find out the client's IP address from the headers available to us * * @param ServerRequestInterface $request PSR-7 Request * @return string */ protected function determineClientIpAddress($request) { $ipAddress = null; $serverParams = $request->getServerParams(); if (isset($serverParams['REMOTE_ADDR']) && $this->isValidIpAddress($serverParams['REMOTE_ADDR'])) { $ipAddress = $serverParams['REMOTE_ADDR']; } $checkProxyHeaders = $this->checkProxyHeaders; if ($checkProxyHeaders && !empty($this->trustedProxies)) { if (!in_array($ipAddress, $this->trustedProxies)) { $checkProxyHeaders = false; } } if ($checkProxyHeaders) { foreach ($this->headersToInspect as $header) { if ($request->hasHeader($header)) { $ip = trim(current(explode(',', $request->getHeaderLine($header)))); if ($this->isValidIpAddress($ip)) { $ipAddress = $ip; break; } } } } return $ipAddress; }
/** * Proxy to ServerRequestInterface::hasHeader() * * {@inheritdoc} */ public function hasHeader($header) { return $this->psrRequest->hasHeader($header); }