Php http auth fastcgi

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

http basic authentication broken with PHP as cgi/fastCGI under Apache #1813

http basic authentication broken with PHP as cgi/fastCGI under Apache #1813

Bug Good first issue Ideal for your first contribution! (some Symfony experience may be required) HttpFoundation

Comments

The keys PHP_AUTH_USER and PHP_AUTH_PW are not present in the superglobal $_SERVER, so http basic authentication needs to be handled a little differently.

This also affects functional tests which require http basic auth to authenticate.

Читайте также:  Permutations and combinations in python

Basically the workaround is two parts:

  1. A rewrite rule to pack the username and password into an environment variable: RewriteEngine on RewriteRule .\* — [E=HTTP_AUTHORIZATION:%,L]
  2. Extract the info from the environment variable: list($_SERVER[‘PHP_AUTH_USER’], $_SERVER[‘PHP_AUTH_PW’]) = explode(‘:’ , base64_decode(substr($_SERVER[‘HTTP_AUTHORIZATION’], 6)));

See below for more details.

The text was updated successfully, but these errors were encountered:

@fabpot, should we maybe add some extra abstraction for this to the Request class?

+1, the request should definitly abstract this.

The following works as a temporary workaround:

if( !isset($_SERVER['PHP_AUTH_USER']) ) < if (isset($_SERVER['HTTP_AUTHORIZATION']) && (strlen($_SERVER['HTTP_AUTHORIZATION']) >0)) < list($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']) = explode(':', base64_decode(substr($_SERVER['HTTP_AUTHORIZATION'], 6))); if( strlen($_SERVER['PHP_AUTH_USER']) == 0 || strlen($_SERVER['PHP_AUTH_PW']) == 0 ) < unset($_SERVER['PHP_AUTH_USER']); unset($_SERVER['PHP_AUTH_PW']); >> > 
 RewriteEngine On RewriteRule .* - [E=HTTP_AUTHORIZATION:%,L] RewriteCond % !-f RewriteRule ^(.*)$ app.php [QSA,L] 

It works fine for me with FastCGI and Nginx.

Can you paste the whole output of $_SERVER when not using the workaround?

Here is the output of $_SERVER without the workaround:

 Array ( [ALLUSERSPROFILE] => C:\ProgramData [APPDATA] => C:\windows\system32\config\systemprofile\AppData\Roaming [asl_log] => Destination=file [CLASSPATH] => .;C:\Program Files\Java\jre6\lib\ext\QTJava.zip [CommonProgramFiles] => C:\Program Files\Common Files [COMPUTERNAME] => HP [ComSpec] => C:\windows\system32\cmd.exe [DB2INSTANCE] => DB2 [FP_NO_HOST_CHECK] => NO [LOCALAPPDATA] => C:\windows\system32\config\systemprofile\AppData\Local [NUMBER_OF_PROCESSORS] => 4 [OnlineServices] => Online Services [OS] => Windows_NT [Path] => C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;c:\Program Files\Hewlett-Packard\Drive Encryption\;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\Broadcom\Broadcom 802.11\Driver;C:\Program Files\QuickTime\QTSystem\;C:\Program Files\Zend\ZendServer\bin [PATHEXT] => .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC [PCBRAND] => s [PHPRC] => C:\Program Files\Zend\ZendServer\etc [PHP_FCGI_MAX_REQUESTS] => 10000 [Platform] => BNB [PROCESSOR_ARCHITECTURE] => x86 [PROCESSOR_IDENTIFIER] => x86 Family 6 Model 37 Stepping 5, GenuineIntel [PROCESSOR_LEVEL] => 6 [PROCESSOR_REVISION] => 2505 [ProgramData] => C:\ProgramData [ProgramFiles] => C:\Program Files [PSModulePath] => C:\windows\system32\WindowsPowerShell\v1.0\Modules\ [PTSM_install_path] => c:\Program Files\Hewlett-Packard\HP ProtectTools Security Manager\Bin [PUBLIC] => C:\Users\Public [QTJAVA] => C:\Program Files\Java\jre6\lib\ext\QTJava.zip [SystemDrive] => C: [SystemRoot] => C:\windows [TEMP] => C:\Users\User\AppData\Local\Temp [TMP] => C:\windows\TEMP [USERDOMAIN] => WORKGROUP [USERNAME] => HP$ [USERPROFILE] => C:\windows\system32\config\systemprofile [windir] => C:\windows [AP_PARENT_PID] => 688 [_FCGI_CLIENT_PID_] => 2244 [_FCGI_MUTEX_] => 776 [_FCGI_NTAUTH_IMPERSONATE_] => 1 [_FCGI_SHUTDOWN_EVENT_] => 772 [FCGI_ROLE] => RESPONDER [HTTP_HOST] => localhost [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0 [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 [HTTP_ACCEPT_LANGUAGE] => en-us,en;q=0.5 [HTTP_ACCEPT_ENCODING] => gzip, deflate [HTTP_ACCEPT_CHARSET] => ISO-8859-1,utf-8;q=0.7,*;q=0.7 [HTTP_CONNECTION] => keep-alive [HTTP_COOKIE] => __utma=1.441182227.1321189418.1322498628.1323267653.4; __utmz=1.1321189418.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); ZDEDebuggerPresent=php,phtml,php3; PHPSESSID=nqtap9dur6uja1rjjumcttmc25 [HTTP_CACHE_CONTROL] => max-age=0 [PATH] => C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;c:\Program Files\Hewlett-Packard\Drive Encryption\;C:\Program Files\WIDCOMM\Bluetooth Software\;C:\Program Files\Broadcom\Broadcom 802.11\Driver;"C:\Program Files\Zend\ZendServer\bin";"C:\Program Files\Zend\ZendServer\share\ZendFramework\bin";C:\Program Files\Zend\MySQL51\bin;C:\Program Files\Git\cmd;C:\Program Files\Git\bin;C:\Program Files\TortoiseSVN\bin;C:\Program Files\Common Files\HP\Digital Imaging\bin;C:\Program Files\HP\Digital Imaging\bin\;C:\Program Files\HP\Digital Imaging\bin\Qt\Qt 4.3.3;C:\Program Files\QuickTime\QTSystem\; [COMSPEC] => C:\windows\system32\cmd.exe [WINDIR] => C:\windows [SERVER_SIGNATURE] => [SERVER_SOFTWARE] => Apache/2.2.16 (Win32) mod_ssl/2.2.16 OpenSSL/0.9.8o [SERVER_NAME] => localhost [SERVER_ADDR] => 127.0.0.1 [SERVER_PORT] => 80 [REMOTE_ADDR] => 127.0.0.1 [DOCUMENT_ROOT] => C:/Program Files/Zend/Apache2/htdocs [SERVER_ADMIN] => admin@example.com [SCRIPT_FILENAME] => C:/Program Files/Zend/Apache2/htdocs/MySite/web/app_dev.php [REMOTE_PORT] => 1740 [GATEWAY_INTERFACE] => CGI/1.1 [SERVER_PROTOCOL] => HTTP/1.1 [REQUEST_METHOD] => GET [QUERY_STRING] => [REQUEST_URI] => /MySite/web/app_dev.php/ [SCRIPT_NAME] => /MySite/web/app_dev.php [PATH_INFO] => / [PATH_TRANSLATED] => C:\Program Files\Zend\Apache2\htdocs\index.html [PHP_SELF] => /MySite/web/app_dev.php/ [REQUEST_TIME] => 1324019271 [argv] => Array ( ) [argc] => 0 ) 

Finally I’ve made a working patch for that, I’ll submit it as soon as I figure out how to submit a patch. 😉

Источник

HTTP Authentication в PHP запущеном как CGI/FastCGI/SuExec

HTTP Authentication в PHP запущеном как CGI/FastCGI/SuExec

Admin » 14.04.2014, 20:30 » Сообщение: #1

HTTP Authentication в PHP запущеном как CGI/FastCGI/SuExec

Способ подключения PHP не как SAPI достаточно распространен и удобен, но как и во всем есть нюансы. Я хочу рассказать как можно реализовать такую нужную штуку как HTTP Basic Authentication.

HTTP Basic Authentication — это возможность ограничить доступ к какому-либо http ресурсу (обсуждаем только apache), тоесть тупо попросить логин и пасс. По правилам это делается так

В файлик, например, .htpasswd записывается пароль в виде webuser:qkbPmuht5Gzgc — это md5 алгоритмом зашифрованй пароль, системная функция crypt(). UNIX неумеет хранить пароли в plaintext формате, а вот Windows умеет. Дальше в .httaccess файл записывается что-то подобное

php Код: Выделить всё Развернуть AuthType Basic
AuthUserFile «/home/username/path_to_htpasswd/.htpasswd»
AuthName “Enter valid username and password ! ”
require valid — user

и при обращении к данной директории и всем нижестоящим или файлу как в примере будет автоматически потребован пароль. Это очень удобно так как ненужно делать никаких html форм.

Точно такой же принцип может применяться и в PHP скриптах для ограничения доступа к какому-либо файлу. НО! это все работает только если PHP подсоединен как SAPI (mod_php) модуль.

if (!isset( $_SERVER [ ‘PHP_AUTH_USER’ ])) header ( ‘WWW-Authenticate: Basic realm=»My Realm»‘ );
header ( ‘HTTP/1.0 401 Unauthorized’ );
echo ‘Text to send if user hits Cancel button’ ;
exit ;
> else echo «

Hello,

» . $_SERVER [ ‘PHP_AUTH_USER’ ];
echo «

You entered as your password:

» . $_SERVER [ ‘PHP_AUTH_PW’ ];
>
?>

Вот этот код заставит при вызови скрипта открыть диалоговое окно и попросить логин и пасс, которые в последствии передадутся в переменные $_SERVER[‘PHP_AUTH_USER’] и $_SERVER[‘PHP_AUTH_PW’]

Все замечательно и красиво, но работает только с mod_php, грустно!

В решении этой проблемы может помочь mod_rewrite, вообще очень мощная штука при правильном использовании. Для того чтобы перенаправить в скрипт данные из формы мы используетм вот такое правило в .htaccess файле

Но этого недостаточно, так как данные находятся в несколько неприемлемом формате, поэтому их нужно обработать

php Код: Выделить всё Развернуть list( $_SERVER [ ‘PHP_AUTH_USER’ ], $_SERVER [ ‘PHP_AUTH_PW’ ]) = explode ( ‘:’ , base64_decode ( substr ( $_SERVER [ ‘HTTP_AUTHORIZATION’ ], 6 )));

после этого переменные $_SERVER[‘PHP_AUTH_USER’] и $_SERVER[‘PHP_AUTH_PW’] содержат всю необходимую информацию. Вот работающий пример

php Код: Выделить всё Развернуть if( strpos ( $_SERVER [ ‘HTTP_AUTHORIZATION’ ], ‘:’ )) list ( $_SERVER [ ‘PHP_AUTH_USER’ ], $_SERVER [ ‘PHP_AUTH_PW’ ]) = explode ( ‘:’ , base64_decode ( substr ( $_SERVER [ ‘HTTP_AUTHORIZATION’ ], 6 )));
>;

if (!isset( $_SERVER [ ‘PHP_AUTH_USER’ ])) header ( ‘WWW-Authenticate: Basic realm=»My Realm»‘ );
header ( ‘HTTP/1.0 401 Unauthorized’ );
echo ‘Text to send if user hits Cancel button’ ;
exit ;
> else echo «

Hello,

» . $_SERVER [ ‘PHP_AUTH_USER’ ];
echo «

You entered as your password:

» . $_SERVER [ ‘PHP_AUTH_PW’ ];
>
?>

..Смерть стоит того чтобы жить, а любовь стоит того чтобы ждать..
Admin

Сообщения: 6372 [в теме] Откуда: Москва Группа: Администраторы Благодарил (а): 26 раз(а). Поблагодарили: 185 раз(а). [ Профиль ]

Источник

How to setup HTTP Authentication with Nginx on Ubuntu

Linux Tweaks

Nginx is an HTTP and reverse proxy server which is lightweight as compare to apache. When we need http authentication for secure our site admin login then there is a need to setup HTTP Authentication with our server. So below steps define how to setup HTTP Authentication with Nginx on Ubuntu Server.

Setup HTTP Authentication with Nginx

Install Apache Utils

First we need to install apache utils which require for generate encrypted password for the user using basic authentication. Install apache2-utils using following command –

linuxtweaks ~]#apt-get install apache2-utils

Create user and password

Create a .htpasswd file under your web root directory being served by nginx virtual host. The following command would use to create htpasswd file –

linuxtweaks ~]#htpasswd -c /var/www/vhosts/linuxtweaks.in/.htpasswd linuxuser New password: Re-type new password: Adding password for user linuxuser

You can check the file htpasswd which will look like this –

linuxtweaks ~]#cat /var/www/vhosts/linuxtweaks.in/.htpasswd linuxuser:encryptedpassword

Nginx Configuration

Next we need to configure nginx for using http authentication for our admin login page.Here we can secure whole site or some of pages of our site.

So update nginx virtualhost under /etc/nginx/sites-enabled/linuxtweaks.conf and add below line of code.if secure whole site which is in development or just to secure. Add two line of code in your nginx vhost configuration so your vhost will look like this.

The above code is normal when we don’t have php file. When we have php file and using fastcgi as backend proxy than we have to configure vhost in different way for secure any page.

server < listen 80; server_name linuxtweaks.in; root /var/www/vhosts/linuxtwaeks.in; index index.php index.html index.htm; ######### Whatever code configured in your nginx vhost###### ###### line of code ####### # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 location ~ \.php$ < try_files $uri =404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; > location ~* /wp-login.php < auth_basic "Restricted Area"; auth_basic_user_file /var/www/vhosts/linuxtweaks.in/.htpasswd; try_files $uri =404; fastcgi_pass unix:/var/run/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; > >

Above line of code secure wordpress admin login page with precreated user in .htpasswd.

NOTE :- We have to use php scripts code when define locatoin for any php file to secure otherwise after login successfully your file will goes download as bin file and not executed as php script.

If you configure your site as –

Above code will call the http authentification, but not executed php as scripts so the browser downloads the wp-login.php , when the credentials have been entered, instead of going to the main login screen.

Reload Nginx

Reload/restart nginx server to take effect of your configuration.

linuxtweaks ~]#service nginx reload

Now you can check if your whole site / selected page is secure through http authentication.

To know more about HTTP Authentication please click here

Источник

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