Php get auth header

Authentication¶

The Authentication component allows you to to implement authentication methods which can simply update the request with authentication detail (for example by adding an Authorization header). This is useful when you have to send multiple requests to the same endpoint. Using an authentication implementation, these details can be separated from the actual requests.

Installation¶

$ composer require php-http/message

Authentication Methods¶

Authorization header of the HTTP specification

Authorization header of the HTTP specification

Authorization header of the HTTP specification

Array of param-value pairs

Array of authentication instances

Behaviors of the underlying authentication methods

An authentication instance and a matcher callback

Behavior of the underlying authentication method if the matcher callback passes

Add an arbitrary authentication header

Integration with HTTPlug¶

Normally requests must be authenticated “by hand” which is not really convenient.

If you use HTTPlug, you can integrate this component into the client using the authentication plugin .

Examples¶

General usage looks like the following:

$authentication = new AuthenticationMethod(); /** @var Psr\Http\Message\RequestInterface */ $authentication->authenticate($request); 

Basic Auth¶

use Http\Message\Authentication\BasicAuth; $authentication = new BasicAuth('username', 'password'); 

Bearer¶

use Http\Message\Authentication\Bearer; $authentication = new Bearer('token'); 

WSSE¶

use Http\Message\Authentication\Wsse; $authentication = new Wsse('username', 'password'); 

For better security, also pass the 3rd optional parameter to use a better hashing algorithm than sha1 , e.g.

use Http\Message\Authentication\Wsse; $authentication = new Wsse('username', 'password', 'sha512'); 

Query Params¶

use Http\Message\Authentication\QueryParam; $authentication = new QueryParam([ 'access_token' => '9zh987g86fg87gh978hg9g79', ]); 

Using query parameters for authentication is not safe. Only use it when this is the only authentication method offered by a third party application.

Chain¶

The idea behind this authentication method is that in some cases you might need to authenticate the request with multiple methods.

For example it’s a common practice to protect development APIs with Basic Auth and the regular token authentication as well to protect the API from unnecessary processing:

use Http\Message\Authentication\Chain; $authenticationChain = [ new AuthenticationMethod1(), new AuthenticationMethod2(), ]; $authentication = new Chain($authenticationChain); 

Matching¶

With this authentication method you can conditionally add authentication details to your request by passing a callable to it. When a request is passed, the callable is called and used as a boolean value in order to decide whether the request should be authenticated or not. It also accepts an authentication method instance which does the actual authentication when the condition is fulfilled.

Читайте также:  Php gd jpeg freetype

For example a common use case is to authenticate requests sent to certain paths:

use Http\Message\Authentication\Matching; use Psr\Http\Message\RequestInterface; $authentication = new Matching( new AuthenticationMethod1(), function (RequestInterface $request)  $path = $request->getUri()->getPath(); return 0 === strpos($path, '/api'); > ); 

In order to ease creating matchers for URLs/paths, there is a static factory method for this purpose: createUrlMatcher The first argument is an authentication method, the second is a regular expression to match against the URL:

use Http\Message\Authentication\Matching; $authentication = Matching::createUrlMatcher(new AuthenticationMethod(), '\/api'); 

With this authentication method you can add arbitrary headers.

In the following example, we are setting a X-AUTH-TOKEN header with it’s value:

use Http\Message\Authentication\Header; $authentication = new Header('X-AUTH-TOKEN', '9zh987g86fg87gh978hg9g79'); 

Implement Your Own¶

Implementing an authentication method is easy: only one method needs to be implemented:

use Http\Message\Authentication; use Psr\Http\Message\RequestInterface; class MyAuth implements Authentication  public function authenticate(RequestInterface $request)  // do something with the request // keep in mind that the request is immutable - return the updated // version of the request with the authentication information added // to it. return $request; > > 

© Copyright 2015, The PHP-HTTP Team. Revision 749bb3a1 .

Источник

How to get Authorization header in PHP

In order to construct a secure resource that can be accessed through an API, we must utilize an authorization header with a token or bearer. In this article, I will guide you how to obtain the authorization header, extract the token or bearer. Then authenticate it against a database table and return a JSON output in PHP.

Here is what I have on my system.

PHP already has a built-in function, getallheaders(), that can retrieve all headers. It is useful because it eliminates the need for additional code to be written.

The next step is to check if the key exists in the array. We will use the array_key_exists function. If it does not exist, return an error.

if (!array_key_exists('Authorization', $headers)) < echo json_encode(["error" =>"Authorization header is missing"]); exit; >

In most cases, the token has a keyword of your choice, such as ‘Token‘ or ‘Bearer‘. To check this, we will use the substr function.

if (substr($headers['Authorization'], 0, 6) !== 'Token ') < echo json_encode(["error" =>"Token keyword is missing"]); exit; >
if (substr($headers['Authorization'], 0, 7) !== 'Bearer ') < echo json_encode(["error" =>"Bearer keyword is missing"]); exit; >

Now we will extract the actual token. This is for Token keyword.

$token = trim(substr($headers['Authorization'], 6));

We will also need to check the validity of the token against a database table. I am using my own framework for this purpose, but you can also accomplish this by connecting to the database and running a query similar to the following:

$host = "host"; $dbname = "database"; $username = "username"; $password = "password"; $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = "SELECT COUNT(t.token) as totalRows FROM tokens as t WHERE t.token = :token"; $data = [ "token" => $token ]; $stmt = $conn->prepare($query); $stmt->execute($data); $result = $stmt->fetch(PDO::FETCH_ASSOC); $count = $result['totalRows'];
$host = "host"; $dbname = "database"; $username = "username"; $password = "password"; $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password); $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $headers = getallheaders(); if (!array_key_exists('Authorization', $headers)) < echo json_encode(["error" =>"Authorization header is missing"]); exit; > else < if (substr($headers['Authorization'], 0, 6) !== 'Token ') < echo json_encode(["error" =>"Token keyword is missing"]); exit; > else < $token = trim(substr($headers['Authorization'], 6)); $query = "SELECT COUNT(t.token) as totalRows FROM tokens as t WHERE t.token = :token"; $data = [ "token" =>$token ]; $stmt = $conn->prepare($query); $stmt->execute($data); $result = $stmt->fetch(PDO::FETCH_ASSOC); $count = $result['totalRows']; if ($count == 0) < echo json_encode(["error" =>"Authorization failed"]); exit; > else < ## continue the rest of your stuff >> >

If you are using Bearer keyword, remember to change the position to 7 in substr function.

Something like this will work.

$token = trim(substr($headers['Authorization'], 7));

Источник

Получение пользовательского заголовка авторизации из входящего запроса PHP

Поэтому я пытаюсь разобрать входящий запрос в PHP, который имеет следующий набор заголовков:

Authorization: Custom Username 

Простой вопрос: как, на мой взгляд, я могу это понять? Если это была Authorization: Basic , я мог бы получить имя пользователя из $_SERVER[«PHP_AUTH_USER»] . Если это было X-Custom-Authorization: Username , я мог бы получить имя пользователя из $_SERVER[«HTTP_X_CUSTOM_AUTHORIZATION»] . Но ни один из них не задан пользовательской авторизацией, var_dump($_SERVER) указывает на заголовок (в частности, AUTH_TYPE отсутствует), а функции PHP5, такие как get_headers() работают только с ответами на исходящие запросы. Я запускаю PHP 5 на Apache с установленной установкой Ubuntu.

Solutions Collecting From Web of «Получение пользовательского заголовка авторизации из входящего запроса PHP»

Если вы собираетесь использовать Apache, возможно, вам захочется взглянуть на apache_request_headers() .

Для аутентификации на токенах:

 $token = null; $headers = apache_request_headers(); if(isset($headers['Authorization'])) < $matches = array(); preg_match('/Token token="(.*)"/', $headers['Authorization'], $matches); if(isset($matches[1]))< $token = $matches[1]; >> 

Для фона, почему Apache отфильтровывает заголовок Authorization : https://stackoverflow.com/a/17490827

Решения, в зависимости от того, какой модуль Apache используется для передачи запроса в приложение:

Другие хаки – массирование заголовков в этом вопросе:

  • Отсутствует заголовок заголовка запроса. Заголовок авторизации в Symfony 2?
  • Apache 2.4 + PHP-FPM и заголовки авторизации

Добавьте этот код в свой .htaccess

RewriteEngine On RewriteRule .* - [e=HTTP_AUTHORIZATION:%] 

Передайте свой заголовок, как Authorization: и, наконец, вы получите код авторизации с помощью $_SERVER[‘HTTP_AUTHORIZATION’]

  • PHP MYSQL UPDATE, если Exist или INSERT, если нет?
  • Функциональность сайта нарушена или взломана
  • PHP-массив из YAML с Symfony
  • PHP Ajax Shell Exec () Прогресс
  • Создать квадрат 1: 1 thumbnail в PHP
  • Удалите несколько пустых узлов с помощью SimpleXML
  • Вставка объекта данных PHP не выполняется
  • Разбиение и сохранение строки в массиве php
  • Предупреждение: невозможно изменить информацию заголовка – уже отправленные заголовки
  • проверьте, существует ли изображение php
  • Изменение значения переменной PHP с помощью AJAX
  • как создать уникальный код отслеживания
  • CodeIgniter BASEPATH
  • Как получить количество отдельных узлов XML?
  • Поиск с разделенным запятой значением mysql

Источник

PHP — A primer on the Basic Authorization Header

markus-voetter-525896-unsplash

HTTP basic authentication is a simple challenge and response mechanism with which a server can request authentication information (a user ID and password) from a client. The client passes the authentication information to the server in an Authorization header.

In various PHP projects that I’ve worked on, very often I have come across code that relies on using PHP’s explode function to generate an array from a string based on a delimiter.

This is also the case for how many devs choose to parse the Basic Authorization header:

The code above might seem ok, and maybe with some additional user input validation it could work, but not in all cases.

Let’s have a look at Symfony’s approach to deal with this:

Why is the second option better ?

First of all, it checks if the header passed really starts with the string Basic (case insensitive). Then, it uses explode to split the decoded credentials, but it passes along a less known third parameter:

Using explode(‘:’, ‘username:pass:123’, 2) will generate an array of 2 elements: username and pass:123 . This prevents the possibility of obtaining a shorter password string if it contains a colon(‘:’).

Hey, but what about usernames with colons .

According to the ‘RFC 7617’ usernames with a colon can not be used in an Authorization header.

Here’s the relevant portion from the RFC:

. Furthermore, a user-id containing a colon character is invalid, as the first colon in a user-pass string separates user-id and password from one another; text after the first colon is part of the password. User-ids containing colons cannot be encoded in user-pass strings.

PHP-CGI and the Basic Authorization Header

On servers running Apache with the php-cgi handler, the server will not pass the HTTP Authorization header to PHP.

To avoid smashing your keyboard, just add this to your .htaccess file:

 RewriteEngine On RewriteCond % ^(.+)$ RewriteRule .* - [E=HTTP_AUTHORIZATION:%]

Security concerns

The basic authorization header is only secure if your connection is done over HTTPS since otherwise the credentials are sent in encoded plain text (not encrypted) over the network which is a huge security issue.

To conclude, the various implementation flaws that basic authentication has can cause serious concerns. However, since it is already a part of many applications, the best thing we can do is to take all possible precautions.

Источник

Оцените статью