當前位置: 首頁>>代碼示例>>PHP>>正文


PHP ServerRequestInterface::getHeader方法代碼示例

本文整理匯總了PHP中Psr\Http\Message\ServerRequestInterface::getHeader方法的典型用法代碼示例。如果您正苦於以下問題:PHP ServerRequestInterface::getHeader方法的具體用法?PHP ServerRequestInterface::getHeader怎麽用?PHP ServerRequestInterface::getHeader使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在Psr\Http\Message\ServerRequestInterface的用法示例。


在下文中一共展示了ServerRequestInterface::getHeader方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的PHP代碼示例。

示例1: authorize

 /**
  * Authenticates that the user is allowed to make call to the route.
  *
  * @param ServerRequestInterface ServerRequestInterface $request  PSR-7 standard for receiving client request
  * @param ResponseInterface      ResponseInterface      $response PSR-& standard for sending server response
  * @param function                                      $next     callback function for calling next method
  *
  * @return ResponseInterface HTTP response of client request
  */
 public function authorize(ServerRequestInterface $request, $response, $next)
 {
     if (empty($request->getHeader('Authorization'))) {
         $response = $response->withStatus(400);
         $response->getBody()->write(json_encode(['message' => 'Token not found']));
         return $response;
     }
     //Get token for accessing this route
     $token = $request->getHeader('Authorization')[0];
     try {
         //Decode token to get object of data
         $decodedToken = Auth::decodeToken($token);
         //Extract the user id from decoded token
         $uid = $decodedToken->data->uid;
         $user = User::find($uid);
         //Check if user exist with the user id
         if ($user != null) {
             if ($user->isTokenValid($decodedToken)) {
                 $response = $next($request, $response);
             }
         } else {
             $response = $response->withStatus(401);
             $response->getBody()->write(json_encode(['message' => 'User does not exist']));
         }
     } catch (TokenExpirationException $ex) {
         $response = $response->withStatus(401);
         $response->getBody()->write(json_encode(['message' => $ex->getMessage()]));
     } catch (\Exception $ex) {
         $response = $response->withStatus(400);
         $response->getBody()->write(json_encode(['message' => $ex->getMessage()]));
     }
     return $response;
 }
開發者ID:andela-gjames,項目名稱:Emoji-API,代碼行數:42,代碼來源:Middleware.php

示例2: getRealUri

 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;
 }
開發者ID:corporateanon,項目名稱:cisco-twitter,代碼行數:11,代碼來源:ProxiedHttpsSupport.php

示例3: __invoke

 /**
  * @inheritDoc
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $userId = $request->getHeader('id')[0];
     $resource = $this->getDomainByRoute($request);
     $this->checkAcl($userId, $resource);
     return $next($request, $response);
 }
開發者ID:andypoorman,項目名稱:wheniwork,代碼行數:10,代碼來源:AclMiddleware.php

示例4: findClient

 /**
  * {@inheritdoc}
  */
 public function findClient(ServerRequestInterface $request, &$client_credentials = null)
 {
     $header = $request->getHeader($this->header_name);
     if (is_array($header) && 1 === count($header)) {
         return $header[0];
     }
 }
開發者ID:spomky-labs,項目名稱:oauth2-server-library,代碼行數:10,代碼來源:None.php

示例5: __invoke

 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');
 }
開發者ID:dyorg,項目名稱:slim-token-authentication,代碼行數:35,代碼來源:TokenSearch.php

示例6: handle

 /**
  * @param Request $request
  * @return JsonResponse|EmptyResponse
  */
 public function handle(Request $request)
 {
     $actor = $request->getAttribute('actor');
     $Referer = $request->getHeader('Referer');
     $params = array_only($request->getParsedBody(), ['identification', 'password']);
     $response = $this->apiClient->send(TokenController::class, $actor, [], $params);
     if ($response->getStatusCode() === 200) {
         $data = json_decode($response->getBody());
         $session = $request->getAttribute('session');
         $this->authenticator->logIn($session, $data->userId);
         $token = AccessToken::find($data->token);
         event(new UserLoggedIn($this->users->findOrFail($data->userId), $token));
         $response = FigResponseCookies::set($response, SetCookie::create("lastLoginName")->withValue($request->getParsedBody()['identification'])->withPath('/'));
         $response = $this->rememberer->remember($response, $token);
     } elseif ($response->getStatusCode() === 401) {
         $responseNew = $this->apiClient->send(PingxxTokenController::class, $actor, [], $params);
         if ($responseNew->getStatusCode() === 200) {
             $data = json_decode($responseNew->getBody());
             $session = $request->getAttribute('session');
             $this->authenticator->logIn($session, $data->userId);
             $token = AccessToken::find($data->token);
             event(new UserLoggedIn($this->users->findOrFail($data->userId), $token));
             $responseNew = FigResponseCookies::set($responseNew, SetCookie::create("lastLoginName")->withValue($request->getParsedBody()['identification'])->withPath('/')->withDomain('dashboard.pingxx.com'));
             $responseNew = $this->rememberer->remember($responseNew, $token);
             return $responseNew;
         } else {
             return $response;
         }
     }
     return $response;
 }
開發者ID:go-wyvern,項目名稱:pingxx-account,代碼行數:35,代碼來源:PingxxLoginController.php

示例7: validateAuthorization

 /**
  * {@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');
     }
 }
開發者ID:tylerian,項目名稱:illuminate-oauth2-server,代碼行數:36,代碼來源:BearerTokenValidator.php

示例8: validateToken

 public function validateToken(ServerRequestInterface $request, ResponseInterface $response)
 {
     $authHeader = $request->getHeader('HTTP_AUTHORIZATION');
     if (empty($authHeader)) {
         $authHeader = apache_request_headers();
         if (empty($authHeader['Authorization'])) {
             throw (new OAuth2Exception('Authorization header is missing'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403));
         }
         $authHeader = $authHeader['Authorization'];
     } else {
         $authHeader = $authHeader[0];
     }
     list($token) = sscanf($authHeader, 'Bearer %s');
     if (!$token) {
         throw (new OAuth2Exception('Token is missing in the request'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403));
     }
     try {
         $token = (new Parser())->parse($token);
     } catch (\Exception $e) {
         throw (new OAuth2Exception('Token was tampered'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403));
     }
     if ($token->getClaim('exp') <= time()) {
         throw (new OAuth2Exception('Token expired'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403));
     }
     $this->info['id'] = $token->getClaim('sub');
     foreach (explode(',', $token->getClaim('cc')) as $customClaim) {
         $this->info[$customClaim] = $token->getClaim($customClaim);
     }
     if (!$token->verify(new Sha256(), $this->config['public-key'])) {
         throw (new OAuth2Exception('Token was tampered'))->displayMessage(OAuth2Exception::FORBIDDEN)->response($response->withStatus(403));
     }
     return $response;
 }
開發者ID:marcoazn89,項目名稱:oauth2-password-grant,代碼行數:33,代碼來源:OAuth2.php

示例9: back

/**
 * @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();
}
開發者ID:Festiv,項目名稱:Festiv,代碼行數:12,代碼來源:functions.php

示例10: execute

 public function execute(Request $req, Response $res, callable $next = null)
 {
     try {
         $name = urldecode($req->getAttribute('name'));
         $collection = $this->boot()->get('store')->getCollection($name);
         $contenttype = $req->getHeader('Content-Type');
         if (false !== strpos($contenttype[0], 'json')) {
             $body = json_decode($req->getBody(), true);
         } else {
             $body = $req->getParsedBody();
         }
         if (!$body) {
             throw new \RuntimeException('no request body');
         }
         $data = $collection->save($collection->item()->setData($body))->getData();
         if (isset($body['@labels'])) {
             foreach ($body['@labels'] as $label) {
                 $this->boot()->get('store')->setLabel($data['id'], $label['_label_name'], $label['_label_group'], true);
             }
         }
         if (isset($body['@properties'])) {
             foreach ($body['@properties'] as $property) {
                 $this->boot()->get('store')->setProperty($data['id'], $property['_property_name'], $property['_property_value'], $property['_property_idx'], $property['_property_type'], $property['_property_sys_type_id'], true);
             }
         }
         $data['@labels'] = $this->boot()->get('store')->getLabels($data['id']);
         $data['@properties'] = $this->boot()->get('store')->getProperties($data['id']);
         return $next($req, new JsonResponse(['status' => 'ok', 'data' => $data]));
     } catch (\Exception $ex) {
         return new JsonResponse(['status' => 'error', 'error' => $ex->getMessage()], 500);
     }
 }
開發者ID:rostmefpoter,項目名稱:bh,代碼行數:32,代碼來源:post.php

示例11: __invoke

 /**
  * Example middleware invokable class
  *
  * @param  \Psr\Http\Message\ServerRequestInterface $request  PSR7 request
  * @param  \Psr\Http\Message\ResponseInterface      $response PSR7 response
  * @param  callable                                 $next     Next middleware
  *
  * @return \Psr\Http\Message\ResponseInterface
  */
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     $auth = $request->getHeader('Authenticate');
     if ($request->getMethod() === 'GET') {
         // Get is allowed without authentication
         // Rate-Limit is handlede by another Middleware
         return $next($request, $response);
     }
     if (!$auth) {
         $response = $response->withHeader('WWW-Authenticate', 'Bearer realm="callingallpapers", error="no token", error_desciption="No Access-Token provided"');
         $response = $response->withStatus(401);
         return $response;
     }
     $bearer = explode(' ', $auth[0]);
     if (!isset($bearer[1])) {
         $response = $response->withHeader('WWW-Authenticate', 'Bearer realm="callingallpapers", error="no token", error_desciption="No Access-Token provided"');
         $response = $response->withStatus(401);
         return $response;
     }
     $bearer = $bearer[1];
     $upl = new UserPersistenceLayer($this->app->getContainer()['pdo']);
     try {
         $user = $upl->getUserForToken($bearer);
     } catch (\Exception $e) {
         $response = $response->withHeader('WWW-Authenticate', 'Bearer realm="callingallpapers", error="invalid token", error_desciption="Invalid Access-Token provided"');
         $response = $response->withStatus(401);
         return $response;
     }
     $request = $request->withAttribute('user', $user['user']);
     return $next($request, $response);
 }
開發者ID:heiglandreas,項目名稱:callingallpapers-api_old,代碼行數:40,代碼來源:OAuth.php

示例12: __construct

 /**
  * @param PayloadInterface $payload
  */
 public function __construct(PayloadInterface $payload, ServerRequestInterface $request, ShiftMapper $shiftMapper)
 {
     $this->payload = $payload;
     $this->shiftMapper = $shiftMapper;
     //userId has already been verified by the AuthAdapter by this point
     $this->userId = (int) $request->getHeader('id')[0];
 }
開發者ID:andypoorman,項目名稱:wheniwork,代碼行數:10,代碼來源:GetEmployeeShifts.php

示例13: isJsonRpc

 /**
  * Returns true if a JSON-RCP request has been received
  * @return boolean
  */
 public function isJsonRpc()
 {
     // https://github.com/oscarotero/psr7-middlewares/blob/c16c64fe5ddbfa2a62fb1169847a526c0e7a5401/src/Utils/Helpers.php
     $method = $this->request->getMethod();
     $type = $this->request->getHeader('content-type');
     //$type = strtolower($request->getHeaderLine('X-Requested-With')) === 'xmlhttprequest';
     $result = $method == 'POST' && !empty($type[0]) && strpos($type[0], 'application/json') !== false;
     return $result;
 }
開發者ID:odan,項目名稱:molengo,代碼行數:13,代碼來源:Http.php

示例14: isValidHubSignature

 /**
  * @return bool
  */
 private function isValidHubSignature()
 {
     $headers = $this->request->getHeader('X-Hub-Signature');
     if (empty($headers)) {
         return false;
     }
     $signature = XHubSignature::parseHeader($headers[0]);
     return XHubSignature::validate($this->getBody(), $this->secret, $signature);
 }
開發者ID:tgallice,項目名稱:fb-messenger-sdk,代碼行數:12,代碼來源:WebhookRequestHandler.php

示例15: isUpload

 public function isUpload(ServerRequestInterface $request)
 {
     $contentTypes = $request->getHeader('Content-Type');
     foreach ($contentTypes as $contentType) {
         if (false !== strpos($contentType, 'multipart/form-data')) {
             return count($request->getUploadedFiles()) > 0;
         }
     }
     return false;
 }
開發者ID:danielbragaalmeida,項目名稱:extdirect,代碼行數:10,代碼來源:Router.php


注:本文中的Psr\Http\Message\ServerRequestInterface::getHeader方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。