本文整理汇总了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;
}
示例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;
}
示例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);
}
示例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];
}
}
示例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');
}
示例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;
}
示例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');
}
}
示例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;
}
示例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();
}
示例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);
}
}
示例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);
}
示例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];
}
示例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;
}
示例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);
}
示例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;
}