--- title: HTTP авторизация slug: Web/HTTP/Authentication tags: - Авторизация - Разграничение доступа - Руководство translation_of: Web/HTTP/Authentication original_slug: Web/HTTP/Авторизация ---
{{HTTPSidebar}}

HTTP предоставляет набор инструментов для разграничения доступа к ресурсам и авторизацией. Самой распространённой схемой HTTP авторизации является "Basic" (базовая) авторизация. Данное руководство описывает основные возможности HTTP авторизации и показывает способы ограничения доступа к вашему серверу с её использованием.

Общий механизм HTTP авторизации

{{RFC("7235")}} определяет средства HTTP авторизации, которые может использовать сервер для {{glossary("запроса")}} у клиента аутентификационной информации. Сценарий запрос-ответ подразумевает, что вначале сервер отвечает клиенту со статусом {{HTTPStatus("401")}} (Unauthorized) и предоставляет информацию о порядке авторизации через заголовок {{HTTPHeader("WWW-Authenticate")}}, содержащий хотя бы один метод авторизации. Клиент, который хочет авторизоваться, может сделать это, включив в следующий запрос заголовок {{HTTPHeader("Authorization")}} с требуемыми данными. Обычно, клиент отображает запрос пароля пользователю, и после получения ответа отправляет запрос с пользовательскими данными в заголовке Authorization.

В случае базовой авторизации как на иллюстрации выше, обмен должен вестись через HTTPS (TLS) соединение, чтобы обеспечить защищённость.

Прокси-авторизация

Этот же механизм запроса и ответа может быть использован для прокси-авторизации. В таком случае ответ посылает промежуточный прокси-сервер, который требует авторизации. Поскольку обе формы авторизации могут использоваться одновременно, для них используются разные заголовки и коды статуса ответа. В случае с прокси, статус-код запроса {{HTTPStatus("407")}} (Proxy Authentication Required) и заголовок {{HTTPHeader("Proxy-Authenticate")}}, который содержит хотя бы один запрос, относящийся к прокси-авторизации, а для передачи авторизационных данных прокси-серверу используется заголовок {{HTTPHeader("Proxy-Authorization")}}.

Доступ запрещён

Если (прокси) сервер получает корректные учётные данные, но они не подходят для доступа к данному ресурсу, сервер должен отправить ответ со статус кодом {{HTTPStatus("403")}} Forbidden. В отличии от статус кода {{HTTPStatus("401")}} Unauthorized или {{HTTPStatus("407")}} Proxy Authentication Required, аутентификация для этого пользователя не возможна.

Аутентификация с помощью изображений

Аутентификация с помощью изображений, загружаемых из разных источников, была до недавнего времени потенциальной дырой в безопасности. Начиная с Firefox 59, изображения, загружаемые из разных источников в текущий документ, больше не запускают диалог HTTP-аутентификации, предотвращая тем самым кражу пользовательских данных (если нарушители смогли встроить это изображение в страницу).

Кодировка символов HTTP аутентификации

Браузеры используют кодировку utf-8 для имени пользователя и пароля. Firefox использовал ISO-8859-1, но она была заменена utf-8 с целью уравнения с другими браузерами, а также чтобы избежать потенциальных проблем (таких как {{bug(1419658)}}).

WWW-Authenticate and Proxy-Authenticate headers

{{HTTPHeader("WWW-Authenticate")}} и {{HTTPHeader("Proxy-Authenticate")}} заголовки ответа которые определяют методы, что следует использовать для получения доступа к ресурсу. Они должны указывать, какую схему аутентификации использовать, чтобы клиент, желающий авторизоваться, знал, какие данные предоставить. Синтаксис для этих заголовков следующий:

WWW-Authenticate: <type> realm=<realm>
Proxy-Authenticate: <type> realm=<realm>

Here, <type> is the authentication scheme ("Basic" is the most common scheme and introduced below). The realm is used to describe the protected area or to indicate the scope of protection. This could be a message like "Access to the staging site" or similar, so that the user knows to which space they are trying to get access to.

Authorization and Proxy-Authorization headers

The {{HTTPHeader("Authorization")}} and {{HTTPHeader("Proxy-Authorization")}} request headers contain the credentials to authenticate a user agent with a (proxy) server. Here, the type is needed again followed by the credentials, which can be encoded or encrypted depending on which authentication scheme is used.

Authorization: <type> <credentials>
Proxy-Authorization: <type> <credentials>

Authentication schemes

The general HTTP authentication framework is used by several authentication schemes. Schemes can differ in security strength and in their availability in client or server software.

The most common authentication scheme is the "Basic" authentication scheme which is introduced in more details below. IANA maintains a list of authentication schemes, but there are other schemes offered by host services, such as Amazon AWS. Common authentication schemes include:

Basic authentication scheme

The "Basic" HTTP authentication scheme is defined in {{rfc(7617)}}, which transmits credentials as user ID/password pairs, encoded using base64.

Security of basic authentication

As the user ID and password are passed over the network as clear text (it is base64 encoded, but base64 is a reversible encoding), the basic authentication scheme is not secure. HTTPS / TLS should be used in conjunction with basic authentication. Without these additional security enhancements, basic authentication should not be used to protect sensitive or valuable information.

Restricting access with Apache and basic authentication

To password-protect a directory on an Apache server, you will need a .htaccess and a .htpasswd file.

The .htaccess file typically looks like this:

AuthType Basic
AuthName "Access to the staging site"
AuthUserFile /path/to/.htpasswd
Require valid-user

The .htaccess file references a .htpasswd file in which each line contains of a username and a password separated by a colon (":"). You can not see the actual passwords as they are encrypted (md5 in this case). Note that you can name your .htpasswd file differently if you like, but keep in mind this file shouldn't be accessible to anyone. (Apache is usually configured to prevent access to .ht* files).

aladdin:$apr1$ZjTqBB3f$IF9gdYAGlMrs2fuINjHsz.
user2:$apr1$O04r.y2H$/vEkesPhVInBByJUkXitA/

Restricting access with nginx and basic authentication

For nginx, you will need to specify a location that you are going to protect and the auth_basic directive that provides the name to the password-protected area. The auth_basic_user_file directive then points to a .htpasswd file containing the encrypted user credentials, just like in the Apache example above.

location /status {
    auth_basic           "Access to the staging site";
    auth_basic_user_file /etc/apache2/.htpasswd;
}

Access using credentials in the URL

Many clients also let you avoid the login prompt by using an encoded URL containing the username and the password like this:

https://username:password@www.example.com/

The use of these URLs is deprecated. In Chrome, the username:password@ part in URLs is even stripped out for security reasons. In Firefox, it is checked if the site actually requires authentication and if not, Firefox will warn the user with a prompt "You are about to log in to the site “www.example.com” with the username “username”, but the website does not require authentication. This may be an attempt to trick you.".

See also