|
|
Autoryzacja HTTP jest obs�ugiwana przez PHP tylko wtedy, gdy PHP pracuje
jako modu� Apache'a, nie jest dost�pna w trybie CGI. W skrypcie mo�na u�y�
funkcji header() by wys�a� do przegl�darki komunikat
"Wymagana autoryzacja", co spowoduje wy�wietlenie okienka z polami
U�ytkownik i Has�o. Po wype�nieniu przez u�ytkownika tych p�l, URL
zawieraj�cy skrypt PHP zostanie ponownie wywo�any ze zmiennymi
$PHP_AUTH_USER, $PHP_AUTH_PW i $PHP_AUTH_TYPE zawieraj�cymi odpowiednio
nazw� u�ytkownika, has�o i typ autoryzacji. Obecnie obs�ugiwany jest
jedynie typ "Basic". Wi�cej informacji znajdziesz w opisie funkcji
header().
Przyk�adowy skrypt wymuszaj�cy autoryzacj� klienta:
Przyk�ad 17-1. Autoryzacja HTTP <?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header("WWW-Authenticate: Basic realm=\"My Realm\"");
header("HTTP/1.0 401 Unauthorized");
echo "Tekst do wys�ania, je�li u�ytkownik wci�nie przycisk Anuluj\n";
exit;
} else {
echo "<p>Hej {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>Twoje has�o to {$_SERVER['$PHP_AUTH_PW']}.</p>";
}
?> |
|
Notatka:
Nale�y uwa�a� z linijkami dodawanymi do nag��wka HTTP. W celu zachowania
maksymalnej zgodno�ci ze wszystkimi klientami, s�owo Basic powinno
zaczyna� si� du�� liter� "B", warto�� realm powinna by� otoczona
cudzys�owami (nie apostrofami), i dok�adnie jeden znak odst�pu powinien
poprzedza� kod 401 w linii "HTTP/1.0 401".
Zamiast wy�wietla� warto�ci $PHP_AUTH_USER i $PHP_AUTH_PW, zapewne
zechcesz sprawdzi� poprawno�� nazwy u�ytkownika i has�a. Na przyk�ad
poprzez zapytanie do bazy danych lub odnalezienie u�ytkownika w pliku dbm.
Nale�y uwa�a� na kapry�ne przegl�darki Internet Explorer. S� wra�liwe na
kolejno�� wysy�anych nag��wk�w HTTP. Wys�anie nag�owka
WWW-Authenticate przed
HTTP/1.0 401 powinno rozwi�za� problem.
Aby zapobiec sytuacji w kt�rej kto� napisze skrypt wykradaj�cy has�o
wys�ane tradycyjnym zewn�trznym mechanizmem, zmienne PHP_AUTH nie b�d�
ustawiane, je�li dla danej strony aktywna jest autoryzacja zewn�trzna.
W tym wypadku, aby uzyska� nazw� u�ytkownika zautoryzowanego zewn�trznie,
nale�y skorzysta� ze zmiennej $REMOTE_USER.
Notatka:
Aby wykry� czy mia�a miejsce zewn�trzna autoryzacja, PHP sprwadza
obecno�� dyrektywy AuthType. Pami�taj zatem, by
nie stosowa� tej dyrektywy w miejscach, gdzie b�dzie u�ywana autoryzacja
PHP. Inaczej ka�da pr�ba autoryzacji zako�czy si� niepowodzeniem.
Powy�sza metoda nie zapobiega jednak wykradaniu hase� do stron wymagaj�cych
autoryzacji przez kogo�, kto na tym samym serwerze kontroluje strony nie
wymagaj�ce autoryzacji.
Zar�wno Netscape Navigator jak i Internet Explorer opr�ni� bufor
autoryzacji po otrzymaniu od serwera kodu 401. Mo�na w ten spos�b
wylogowani� u�ytkownika i zmusi� go do ponownego wys�ania nazwy u�ytkownika
i has�a. Tej metody mo�na u�y� do wylogowania u�ytkownika po okre�lonym
czasie lub stworzenia przycisku "Wyloguj".
Przyk�ad 17-2. Autoryzacja HTTP z wymuszeniem przelogowania <?php
function authenticate() {
header( "WWW-Authenticate: Basic realm=\"Testowy system autoryzacji\"");
header( "HTTP/1.0 401 Unauthorized");
echo "Musisz poda� poprawny login i has�o by wej�� na t� stron�\n";
exit;
}
if (!isset($_SERVER['PHP_AUTH_USER']) || ($SeenBefore == 1 && $OldAuth == $_SERVER['$PHP_AUTH_USER']))) {
authenticate();
}
else {
echo "<p>Witaj: {$_SERVER['$PHP_AUTH_USER']}<br>";
echo "Poprzenio: {$_REQUEST['$OldAuth']}";
echo "<form action='{$_SERVER['$PHP_SELF']}' METHOD='POST'>\n";
echo "<input type='hidden' name='SeenBefore' value='1'>\n";
echo "<input type='hidden' name='OldAuth' value='{$_SERVER['$PHP_AUTH_USER']}'>\n";
echo "<input type='submit' value='Re Authenticate'>\n";
echo "</form></p>\n";
}
?> |
|
Powy�sza metoda nie jest wymagana przez autoryzacj� HTTP typu "Basic",
wi�c nie mo�na na niej polega�. Testy z przegl�dark� Lynx pokaza�y, �e
Lynx nie usuwa danych o autoryzacji po odebraniu od serwera kodu 401,
zatem przej�cie wstecz a nast�pnie do przodu otworzy stron�, chyba, �e
wymagania co do danych autoryzacji zmieni�y si�. U�ytkownik mo�e jednak
u�y� klawisza '_' by usun�c dane o autoryzacji.
Autoryzacja HTTP nie dzia�a je�li u�ywasz serwera Microsoft IIS i
PHP w wersji CGI. Powodem s� pewne ograniczenia IIS.
Notatka:
Je�li w��czony jest tryb bezpieczny,
uid skryptu jest doklejany do pola realm nag��wka
WWW-Authenticate.
User Contributed Notes Autoryzacja HTTP w PHP |
|
21-Jul-1999 09:02 |
|
A few notes on authentication in which it's possible I overlooked some
things. Considering a prior post about using the same salt for all users
so you can match passwords; I think it would be better to not do so, as
you can figure out the salt from the password and match. (Example, salt
in DES if I'm not mistaken is the first 2 characters)
Something I've been trying to figure out is secure apache module PHP on
a multi-user server.
Delima (with postgres)- any user can write a PHP page to read another
users databases. Set your database to connect using username and
password, and any user can read your username and password from wherever
you place them. (use PHP function to read it and as it has to be readable
by your web process for you to read it, they can)
The closest I've come to a solution for this is to run php as a CGI
module with suexec or cgiwrap.
Hopefuly someone else has a better solution; otherwise, something to
think about before you think of your databases as being secure with php
interfacing to them.
|
|
18-Dec-1999 12:42 |
|
Someone gave me a simple solution to the 'logout' problem: add some sort of
timestamp to the basic realm you send in the WWW_Authenticate header. Mine
now is: $realm="RealmName (
".strftime("%c",time())." )";. (btw: the problem
was: 1) IE4 asks for the page one more time after a 401, defeating sending
a 401 once to force a user to log on again. and 2) IE4 remembers the
password, and puts it default in the logon window. Changing the realm
solves these problems, not the 'logon failed' message of NS though).
|
|
09-Feb-2000 05:59 |
|
I had the same problem as above (that is, with apache I can't get the auth
info). The solution I found goes like this:
$headers = getallheaders();
$auth=$headers[authorization];
if ($auth=='') { $auth=$headers[Authorization]; }
if($auth=='')
{
Header("WWW-Authenticate: Basic
realm=\"$PROG_NAME\"");
Header("HTTP/1.0 401 Unauthorized");
}
list($user, $pass) = explode(":", base64_decode(substr($auth,
6)));
|
|
19-May-2000 08:31 |
|
Here is a code for the public sites enabling both logout bottom and timeout
using php+mysql. Working for both browsers.
The part "required" for each user protected page:
<?
function auth () {
Header("WWW-Authenticate: Basic realm=\"ArmFN public
site\"");
Header("HTTP/1.0 401 Unauthorized");
echo "You have to authentificate yourself first \n";
exit;
}
mysql_connect("localhost","train","") or
die("Unable to connect to SQL server");
mysql_select_db( "train") or die( "Unable to select
database");
if(!isset($PHP_AUTH_USER)) {
$timeout =
mktime(date(G),date(i)+10,0,date("m"),date("d"),date("Y"));
mysql_query("update users set login='$timeout' where id='$user' and
pasw='$pass'") or die("k");
auth();
} else {
$pass = $PHP_AUTH_PW;
$user = $PHP_AUTH_USER;
$nowtime =
mktime(date(G),date(i),0,date("m"),date("d"),date("Y"));
$quer2 = mysql_query("select * from users where id='$user' and
pasw='$pass' and login > '$nowtime'") or die("kuk2");
if (mysql_num_rows($quer2) == "0") {
$timeout =
mktime(date(G),date(i)+10,0,date("m"),date("d"),date("Y"));
mysql_query("update users set login='$timeout' where id='$user' and
pasw='$pass'") or die("k");
auth();
}
}
?>
You can have a "logout" bottom with hidden
$go="logout" form element and then have somewhere this part:
if ($do == "logout") {
mysql_connect("localhost","train","") or
die("Unable to connect to SQL server");
mysql_select_db( "train") or die( "Unable to select
database");
mysql_query("update users set login=0 where id='$PHP_AUTH_USER' and
pasw='$PHP_AUTH_PW'") or die("k");
}
|
|
30-Aug-2000 09:04 |
|
Good day.I've solved a problem where IE4 asks for the age one more time
after a 401, defeating sending a 401 once to force a user to log on
again.
function authenticate() {
setcookie("noauth","");
Header( "WWW-authenticate: Basic
realm=\"test\"");
Header( "HTTP/1.0 401 Unauthorized");
echo "You must enter user name";
exit ;
}
if ( !isset($PHP_AUTH_USER) || ($logoff==1) &&
$noauth=="yes" ) {
authenticate();
}
And logoff link -
<a
href="samehtml.phtml?logoff=1">Logoff</a></td>
Dmitry Alyekhin
|
|
16-Oct-2000 09:01 |
|
The new Mozilla browser doesn't seem to like the switched authentication
lines.
This doesn't work (I have build 2000101308):
Header( "WWW-authenticate: Basic realm=\"test\"");
Header( "HTTP/1.0 401 Unauthorized");
The first time you authenticate all seems ok, but the second time it
always returns unauthorized.
This works as it should:
Header( "HTTP/1.0 401 Unauthorized");
Header( "WWW-authenticate: Basic realm=\"test\"");
|
|
10-Mar-2001 08:19 |
|
I suggest to read RFC2617 (HTTP Authentication: Basic and Digest Access
Authentication) and related RFCs.
|
|
05-Apr-2001 05:19 |
|
Thanks to [email protected] for the rfc note needed to solve this
one. This looks like it flushed out the authentication headers on both
Netscape and IE:
Header("WWW-Authenticate: Basic realm=\"Whatever Realm\",
stale=FALSE");
|
|
17-May-2001 09:55 |
|
You may enjoy this tutorial :
|
|
12-Jun-2001 09:53 |
|
This is a good resource for setting up htaccess schemes:
The windows version of apache comes with htpasswd.exe in the apache\bin
directory.
The only thing that present problems is you have to change your .htaccess
file to point to the created password file (ie
C:\directory\passwords.file)....so if you transfer the file back to a *nix
server it wont find your file.
One (temporary) workaround is changing your local httpd.conf file to point
to a different access file:
AccessFileName htaccess.
You just have to make sure to syncronize your access files.
Im not sure if you can point your htaccess to two password files??
AuthName "restricted stuff"
AuthType Basic
AuthUserFile /usr/local/etc/httpd/users
AuthUserFile C:\directory\password.file
require valid-user
|
|
12-Jul-2001 07:51 |
|
If register_globals is turned off PHP_AUTH_USER and PHP_AUTH_PW variables
will not be set, instead they are stored in $HTTP_SERVER_VARS array as
$HTTP_SERVER_VARS['PHP_AUTH_USER'] and HTTP_SERVER_VARS['PHP_AUTH_PW'].
|
|
28-Jan-2002 05:25 |
|
Restrict access by username, password AND ip address:
<?
function authenticate() {
header("WWW-Authenticate: Basic realm=\":-!\"");
header("HTTP/1.0 401 Unauthorized");
print("You must enter a valid login username and password
to access this resource.\n");
exit;
}
if(!isset($PHP_AUTH_USER)){ authenticate(); }
else {
$c=mysql_pconnect("server.name","user","password");
mysql_select_db("dbname",$c);
$q=sprintf("SELECT username,password FROM authenticateTable
WHERE username='%s' AND password=PASSWORD('%s')
AND ipaddress='%s'",
$PHP_AUTH_USER,$PHP_AUTH_PW,$REMOTE_ADDR);
$q=mysql_query($q);
if(mysql_num_rows($q)==0){ authenticate(); }
}
?>
|
|
29-Jan-2002 09:00 |
|
To get it to work with IIS try using this code before setting your
"$auth = 0" and the "if (isset($PHP_AUTH_USER) &&
isset($PHP_AUTH_PW))"
//////////////////////////////////////////
if ($PHP_AUTH_USER == "" && PHP_AUTH_PW == ""
&& ereg("^Basic ", $HTTP_AUTHORIZATION))
{
list($PHP_AUTH_USER, $PHP_AUTH_PW) =
explode(":", base64_decode(substr($HTTP_AUTHORIZATION, 6)));
}
//////////////////////////////////////////
It worked for me on IIS 5 and PHP 4 in ISAPI
|
|
22-Feb-2002 06:09 |
|
I tried the method posted by
[email protected] for a logout feature, which seems to be a problem for
users of http authentication. Tigran's method is perfect, except that
after you log out, you can STILL access the pages by clicking on
"cancel" when prompted again by the Java window.
This will trigger the 401 error. But it will also create an entry in the
history folder.
You will notice the "forward" button on your browser becomes
clickable. You only have to click on the that "forward" button
to be able to access the protected pages.
I have found a solution for this problem by using a little Javascript to
refresh to another page.
Please go to my website for details:
|
|
28-Feb-2002 11:49 |
|
I use apache's built in support for .htaccess, and the following function
to grab user details as required.
Function GetHttpAuth()
{
$headers = getallheaders();
$auth=explode(" ",$headers[Authorization]);
if ($auth=='') { $auth=explode(" " ,$headers[authorization]); }
$authdec=base64_decode($auth[1]);
$autharray=explode(":",$authdec);
$authname=$autharray[0];
$authpass=$autharray[1];
return($autharray);
}
|
|
24-May-2002 02:22 |
|
The definitive HTTP authorization code:
function login_error()
{
echo "error - login process failed."
}
if (!isset($PHP_AUTH_USER))
{
header("WWW-Authenticate: Basic realm=\"Mosaic Authorization
process\"");
header("HTTP/1.0 401 Unauthorized");
//Result if user hits cancel button
login_error();
}
else
{
//check the login and password
if('=>test on login and password<=')
{
//User is logged
...
...
}
else
{
//This re-asks three times the login and password.
header( "WWW-Authenticate: Basic realm=\"Test Authentication
System\"");
header("HTTP/1.0 401 Unauthorized");
//Result if user does not give good login and pass
login_error();
}
}
|
|
02-Jun-2002 05:29 |
|
Using the same salt for all things is a bad idea.
Use the first two letters of the username - this also makes moving to
other .htaccess based systems easier :)
|
|
05-Jun-2002 08:08 |
|
A more elegant way to force a new name/password, cf. example 17-2 (if you
don't mind passing the old user in the query string):
<?
if (isset($PHP_AUTH_USER))
{
if (!isset($prev_user))
{
header("Location: );
exit;
}
else
{
if ($PHP_AUTH_USER == $prev_user)
{
header('WWW-Authenticate: Basic realm="Secure"');
header('HTTP/1.0 401 Unauthorized');
exit;
}
}
}
else
{
header('WWW-Authenticate: Basic realm="Secure"');
header('HTTP/1.0 401 Unauthorized');
exit;
}
?>
The final set of headers is necessary because some browsers seem to unset
$PHP_AUTH_USER when the location header is sent.
|
|
20-Jun-2002 03:30 |
|
Seems that REMOTE_USER is only set in .htaccess Authentification not in PHP
header Authentifications
|
|
|
| |