Authentication PHP user/password - php

I was always using an authentication on PHP that worked perfectly. Looks like this:
function login()
{
header('WWW-Authenticate: Basic realm="Acceso restringido."');
header('HTTP/1.0 401 Unauthorized');
echo "Acceso restringido.\n";
exit;
}
if (!isset($_SERVER['PHP_AUTH_USER'])) {
login();
} else {
if ($_SERVER['PHP_AUTH_USER'] == 'test' && $_SERVER['PHP_AUTH_PW'] == 'test1') {
} else {
login();
}
}
However, I changed hosts to ipage.com and now I get the user/pass prompt window but it never takes the user/pass assigned. It keeps on prompting for user/pass.
I read something about CGI but did not get whether this method is not usable in PHP configured as CGI. Is there any alternative?

Related

http authentication basic not working with parameters in uri

I've an API, I am trying to do basic authentication to call it, the first call with this GET request :
https://example.com/test/api/v1/api
the brower send me the user and password. I can to connect, but if I call a second request with paramters like this :
https://example.com/test/api/v1/api/5
The browser send me again a modal to connect with user and password. At this moment I can't to connect, user and password not reconized...
In the .htaccess file I have :
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
The api.php file contain :
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Authentification canceled';
exit;
} else {
$login = $_SERVER['PHP_AUTH_USER'];
$pwd = $_SERVER['PHP_AUTH_PW'];
if (isset($usersWS) && is_array($usersWS) && isset($usersWS[$login]) && $usersWS[$login] != "" && $usersWS[$login] == $pwd)
//if ($login == "toto" && $pwd= "toto1234")
{
echo "connecte";
}
else
{
header('HTTP/1.0 401 Unauthorized');
echo 'Authentification incorrecte';
exit;
}
I don't know what is wrong ? The POST request works fine.
After few researches, I think it's my .htaccess file that wrong.
When I send this request :
https://example.com/test/api/v1/api.php?id=12
It's work fine ! But with this request :
https://example.com/test/api/v1/api/5
Not working.
So, how I can define rules in .htaccess ?
Thanks for your help
You don't have to use PHP to do the Basic Auth for you, you can put all that in your .htaccess file. For that to work you'll have to generate the user/password combination and put them in a file on the server /path/to/.htpasswd, and then in your .htaccess file you can put this:
AuthType Basic
AuthName "My Website Name"
AuthUserFile /path/to/.htpasswd
Require valid-user

How to do basic authentication on a php CLI

I have a php script on my server which needs to be run by crun. The domain is protected via basic authentication.
The command: sudo /usr/bin/php -auth=user:mypass /home/www/app_cron/example.php
returns: "not authorized"
due to this code:
if ($settings['auth']['passw'] == true){
$settings['auth']['users'] = array_keys($settings['auth']['passw']);
$validated = (in_array($_SERVER['PHP_AUTH_USER'], $settings['auth']['users'])) && ($_SERVER['PHP_AUTH_PW'] == $settings['auth']['passw'][$_SERVER['PHP_AUTH_USER']]);
if (!$validated) {
header('WWW-Authenticate: Basic realm="'.$system['page']['name'].'"');
header('HTTP/1.0 401 Unauthorized');
die ("Not authorized");
}
}
This is a pretty old application and I do not want to mess around much
How can I pass parameters to php via CLI in order to authenticate?

php header() Authentication

Can anyone tell me why this authentication won't work?
This is a breakdown:
1) I'm trying to create a simple authentication using WWW-Authenticate with the php header() function.
2) When I go to the page, the authentication box pops up like so:
3) If I remove the script (see script below), the page loads as expected.4) No matter what password I put in or add/remove the Realm, Stale etc, nothing bites and the Authentication box just keeps looping when I click "Log In".
if( $_SERVER['PHP_AUTH_USER'] != NULL && $_SERVER['PHP_AUTH_PW'] != NULL && $_SERVER['PHP_AUTH_USER'] == ‘admin1’ && $_SERVER['PHP_AUTH_PW'] == ‘pwd1’ ) {
$_SESSION['login_flag'] = true;
} else {
header("WWW-Authenticate: Basic realm=\”Schoolroom\”, stale=FALSE");
header("HTTP/1.0 401 Unauthorized");
print "<h1>401 Unauthorized</h1>";
exit();
}
Can anyone tell me what I am doing wrong? I've also tried in multiple browsers and various computers, same issue.
UPDATE: 10:44am PST, July 5 - This is where I am at so far with modified, updated and commented code:
<?php
header('WWW-Authenticate: Basic realm="Secret page"');
header('HTTP/1.0 401 Unauthorized');
// Status flag:
$LoginSuccessful = false;
// Check username and password:
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])){
$Username = $_SERVER['PHP_AUTH_USER'];
$Password = $_SERVER['PHP_AUTH_PW'];
if ($Username == 'usrnm' && $Password == 'pswrd') {
$LoginSuccessful = true;
}
}
// Login passed successful?
if (!$LoginSuccessful){
/*
** The user gets here if:
**
** 1. The user entered incorrect login data (three times)
** --> User will see the error message from below
**
** 2. Or the user requested the page for the first time
** --> Then the 401 headers apply and the "login box" will
** be shown
*/
// The text inside the realm section will be visible for the
// user in the login box
//header('WWW-Authenticate: Basic realm="Secret page"');
//header('HTTP/1.0 401 Unauthorized');
print "Login failed!\n";
}
else {
// The user entered the correct login data, put
// your confidential data in here:
print 'you reached the secret page!';
}
?>
However, the script does not prompt to login window but instead renders "Login Failed".
We tested it with all available PHP versions 5.0, 5.1, 5.2, 5.3, 5.4, 5.5, 5.6, 7.0, 7.1, but to no avail.
It doesn't look like you're testing to see if $_SESSION['login_flag'] is set and also true.
if(isset($_SESSION['login_flag'] && $_SESSION['login_flag'] == true)) {
//load the page without authentication
}
else {
//ask for authentication
}

PHP - Restrict access to admin page for logged on user

I have a table in my database for users, each user has an auth_level (1-3). On my site I have a admin page for adding/deleting new user accounts, I want to restrict access to this page only to users that have an auth level of 3.
I have been trying to get this to work with sessions but I am stuck. Hoping someone can help me out.
Here is my code for restricting access. Not sure where I have gone wrong.
the check.php start the session.
<?php
require_once('check.php');
//This function returns True if auth level = '3'
//Otherwise it returns False
function CheckAccess()
{
$result = (isset($_SESSION['SESS_AUTH_LEVEL']) && $_SESSION['SESS_AUTH_LEVEL'] == 3 );
if(!$result)
{
header('WWW-Authenticate: Basic realm=“Test restricted area”');
header('HTTP/1.0 401 Unauthorized');
return false;
}
else
{
header("location: admin.php");
}
}
?>
If I log in as a user with auth level 1 or 3, I get the same blank page.
I think you never call CheckAccess(). Calling it maybe fixes your error.
It's perfectly valid to do the following, which your function is doing.
if (this=that) { /*do multiple*/ } else //do single;
However, it appears you are not calling this function? Try this:
<?php
require_once('check.php');
CheckAccess();
?>
You are missing the closing } of your function so all the if statement is seen as part of the method by PHP.
Add a } after $result = and before if
A slightly alternative version that should achieve what you want would be
<?php
function CheckAccess() {
$result = (isset($_SESSION['SESS_AUTH_LEVEL']) && $_SESSION['SESS_AUTH_LEVEL'] == 3 );
return $result;
}
if (CheckAccess()) {
header("location: admin.php");
} else {
header('WWW-Authenticate: Basic realm=“Test restricted area”');
header('HTTP/1.0 401 Unauthorized');
}
The problem is that there is already output before the headers are send:
this need to be changed
<?php
require_once('check.php');
?>
<?php
//This function returns True if auth level = '3'
//Otherwise it returns False
function CheckAccess()
{
...
to this
<?php
require_once('check.php');
//This function returns True if auth level = '3'
//Otherwise it returns False
function CheckAccess()
{
...
because the headers needs to be sent first then the content :)

how to change design /style of the WWW-Authenticate popup box to match my website theme?

Halo there,
I need to change the look /design of the WWW-Authenticate popup box to match my website theme, I don't want it to show the default popup box for authentication when users need to login to secured pages. Below is the PHP script I used to create the WWW-Authenticate popup.
<?php
$_user_ = 'test';
$_password_ = 'test';
session_start();
$url_action = (empty($_REQUEST['action'])) ? 'logIn' : $_REQUEST['action'];
$auth_realm = (isset($auth_realm)) ? $auth_realm : '';
if (isset($url_action)) {
if (is_callable($url_action)) {
call_user_func($url_action);
} else {
echo 'Function does not exist, request terminated';
};
};
function logIn() {
global $auth_realm;
if (!isset($_SESSION['username'])) {
if (!isset($_SESSION['login'])) {
$_SESSION['login'] = TRUE;
header('WWW-Authenticate: Basic realm="'.$auth_realm.'"');
header('HTTP/1.0 401 Unauthorized');
echo 'You must enter a valid login and password';
echo '<p>Try again</p>';
exit;
} else {
$user = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
$password = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
$result = authenticate($user, $password);
if ($result == 0) {
$_SESSION['username'] = $user;
} else {
session_unset($_SESSION['login']);
errMes($result);
echo '<p>Try again</p>';
exit;
};
};
};
}
function authenticate($user, $password) {
global $_user_;
global $_password_;
if (($user == $_user_)&&($password == $_password_)) { return 0; }
else { return 1; };
}
function errMes($errno) {
switch ($errno) {
case 0:
break;
case 1:
echo 'The username or password you entered is incorrect';
break;
default:
echo 'Unknown error';
};
}
function logOut() {
session_start();
session_destroy();
header("Location: index.html");
}
?>
And the following is my code that I use in all pages I need to secure or protect.
<?php
require_once 'auth.php';
echo "You've logged in as {$_SESSION['username']}<br>";
echo '<p>LogOut</p>'
?>
Please help...And recall that the code works fine I only want to change the look. Thanx in advanced :)
Two options:
Javascript
Use javascript to construct a url in the form of http://username:password#domain.com upon form submission, set document.location to the constructed url and the browser will redirect whilst automatically authenticating.
Server Side
Allow the form to submit to itself and use server side code to perform the same redirect - I recommend using a 307 redirect.
In php:
redirect("http://username:password#domain.com", 307);
Downsides
Both versions will still result in the web browser showing the ugly authentication box if the initial username and password submission is incorrect.
If you need to avoid this scenario then you will need to implement your own server side authentication scheme.
More detail
If you can tell me which option you believe you will favour, I can show a little more example code.
Security Implications
There are security implications to using HTTP basic auth. If you do not use SSL then passwords will be sent in cleartext. Using the above methods will send the password in cleartext as part of the URL. There are other security implications too:
https://security.stackexchange.com/questions/988/is-basic-auth-secure-if-done-over-https
Because of these I would always recommend against using http basic auth. Many users may be using the same password for sensitive accounts so it's well worth investing a little time in even a basic authentication system.
You can't change the style of the pop-up box. You will have to create your own login form on your site.

Categories