Basic auth с помошью .htaccess

Web-разработка

Автор: Александр Степанов

1 нояб. 2011 г., 09:58:36  1372


Иногда надо быстро временно закрыть доступ к сайту, а писать красивые вещи, перетаскивать проект в другой каталог — лень. А иногда просто надо сделать закрытую область. Для этого в апаче можно легко с помощью .htaccess файла устроить простую авторизацию. Для этого понадобится

  • полный путь к проекту, например /home/data/virt15566/www.mysite.com/
  • htpasswd программка, лежащая в апаче

Шаг 1 — заливаем в корень сайта .htaccess файл с таким содержанием;

AuthType Basic AuthName "Restricted area" AuthUserFile /home/data/virt15566/www.mysite.com/.htpasswd Require valid-user

Шаг 2 — генерируем содержание файла с помощью программки

c:\>cd C:\Program Files\EasyPHP 3.0\apache\bin C:\Program Files\EasyPHP 3.0\apache\bin>htpasswd -nmb user pass>.htpasswd

В итоге получаем .htpasswd файл вида:

user:$apr1$r2zs21ge$V1CxOLm7r88XNYE0aaJKm.

Опции для генерирования пароля:
OPTIONS

  • -b Use batch mode; i.e., get the password from the command line rather than prompting for it. This option should be used with extreme care, since the password is clearly visible on the command line.
  • -c Create the passwdfile. If passwdfile already exists, it is rewritten and truncated. This option cannot be com- bined with the -n option.
  • -n Display the results on standard output rather than updating a file. This is useful for generating pass- word records acceptable to Apache for inclusion in non-text data stores. This option changes the syntax of the command line, since the passwdfile argument (usually the first one) is omitted. It cannot be com- bined with the -c option.
  • -m Use Apache's modified MD5 algorithm for passwords. Passwords encrypted with this algorithm are transport- able to any platform (Windows, Unix, BeOS, et cetera) running Apache 1.3.9 or later. On Windows and TPF, this flag is the default.
  • -d Use crypt() encryption for passwords. The default on all platforms but Windows and TPF. Though possibly sup- ported by htpasswd on all platforms, it is not sup- ported by the httpd server on Windows and TPF.
  • -s Use SHA encryption for passwords. Faciliates migration from/to Netscape servers using the LDAP Directory Interchange Format (ldif).
  • -p Use plaintext passwords. Though htpasswd will support creation on all platforms, the httpd deamon will only accept plain text passwords on Windows and TPF.
  • passwdfile Name of the file to contain the user name and password. If -c is given, this file is created if it does not already exist, or rewritten and truncated if it does exist.
  • username The username to create or update in passwdfile. If username does not exist in this file, an entry is added. If it does exist, the password is changed.
  • password The plaintext password to be encrypted and stored in the file. Only used with the -b flag.

Официальный мануал — Manual Page: htpasswd

 


Еще можно объединить пользователей в группы и давать доступ не конкретным логинам, а группам. Это можно сделать с помощью директивы AuthGroupFile:
AuthGroupFile /path/to/file/with/groupsВ файле /path/to/file/with/groups создаем группы примерно так: group1: test1 test5 group2: test2 test4 group3: test1 test3 Соответственно, директиву require будем использовать так :
require group group3


Механизмы ограничения доступа, которые реализованы в Apache, позволяют очень гибко управлять правами для пользователей и групп, что является очень важной возможностью. Если углубиться в изучение предмета, Вы сможете узнать и то, что логины и пароли, используемые для авторизации, можно хранить не только в файлах, но и в простейших базах данных формата BerkeleyDB — почитайте документацию по директиве AuthDBGroupFile. Также для хранения данных авторизации можно использовать практически любую СУБД (MySQL или PostgreSQL), но это уже выходит за рамки данного пункта.


Онлайн генератор: Htpasswd Generator
И вообще хороший сайт — htaccesstools.com