How to do basic authentication on a php CLI - php

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?

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

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
}

Digest authentication with encrypted stored password in mysql

I would like to implement digest authentication on my website. However, i have a user table with encrypted user table. I know that i can encrypt $_SERVER['PHP_AUTH_PW'] if i use basic authentication. How can we use the same method for digest authentication?
Are you looking for something like this?
define('MY_REALM', 'THIS IS A SECURE FACILITY, AND I MEAN THAT UNIRONICALLY');
$valid = false;
if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']) {
// Use your DB here; prepared statements are your friend:
$userData = $user->getByUsername($_SERVER['PHP_AUTH_USER']);
if (!empty($userData)) {
$valid = password_verify($_SERVER['PHP_AUTH_PW'], $userData['password_hash']);
}
}
if (!$valid) {
header('WWW-Authenticate: Basic realm="'.MY_REALM.'"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
}
There's little benefit to the HTTP digest authentication method. Just use HTTPS on your website and store passwords with password_hash() and use password_verify() to check them.

Authentication PHP user/password

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?

Display unauthorised page when user clicks 'cancel' (html/php)

I've recently started learning html and php. I'd appreciate it if someone could point me in the right direction: I've made a basic webpage that has basic authentication (to enter it). When the user clicks the cancel button, I would like the browser to do something! All it does is, remain on the page it was on (before the user attempted to access my page). I guess I would like it to display the 401 error. Is the only way to do this, to insert text after:
header('www-authenticate: basic');
?
I've tried redirecting 401 errors in the .htaccess file, though it would seem that the 401 error never occurs (although the server access log says that there was a 401 error). When I redirected my 404 error using .htaccess, it worked.
This is the code that I've got for the authentication:
<?php
$user = array('Michael' => 'Mike');
$pass = array('Michael' => 'fish');
$userSuccess = false;
$passSuccess = false;
if(!isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['PHP_AUTH_PW']))
{
header('http/1.1 401 Unauthorized');
header('www-authenticate: basic');
exit;
}
else
{
foreach($user as $value)
if($_SERVER['PHP_AUTH_USER'] == $value)
$userSuccess = true;
foreach($pass as $value)
if($_SERVER['PHP_AUTH_PW'] == $value)
$passSuccess = true;
if(!$userSuccess || !$passSuccess)
{
header('http/1.1 401 Unauthorized');
header('www-authenticate: basic');
exit;
}
}
?>
Also, if I've done anything stupid in my code, feel free to point it out.
I thought that since I sent the 401 header to the server, and the server logged having received it, it would've displayed some text say, 'Error 401: Unauthorised Access' or something along those lines.
Thanks.
you need to serve the browser with the content for 401. This is not done automatically. The 401 header you send is never really seen by the user. Think of it more as a status flag than content. Programs use that header to detect certain issues and act upon them (i.e. a download manager may detect the 404 header which then shows the download line in its window with a red background and error symbol).
In conclusion then, you need to print the error to the browser yourself
You're going on the right way. I'll do just some changes on your code:
$user = array('Mike' => array('Michael', 'fish'));
if(!isset($_SERVER['PHP_AUTH_USER']) && !isset($_SERVER['PHP_AUTH_PW']))
{
header('http/1.1 401 Unauthorized');
header('www-authenticate: basic');
exit;
}
else
{
$input_user = $_SERVER['PHP_AUTH_USER'];
$input_pw = $_SERVER['PHP_AUTH_PW'];
if($user[$input_user][1] != $input_pw)
{
header('http/1.1 401 Unauthorized');
header('www-authenticate: basic');
exit;
}
}
echo "Hi, " . $user[$input_user][0];
First of all I've changed your users array layout on this layout to this:
Array
(
[Mike] => Array
(
[0] => Michael
[1] => fish
)
)
Read for further info Multidimensional Arrays.
Secund, is your username, then it will have another array with name and password of the user. So you'll not have to user foreach to match your username and pass. BTW, the way you done before your script will allow any user to access with another users pass. If you have other user foo and try user = foo and pass = fish it will gain the access.
Third thing is that you don't need to use $userSuccess and $passSuccess no more. Just to decrease code lenght.
Then I associate two vars to the _SERVER vars, to make easy their use. So you can match then with this sentence: $user[$input_user][1] != $input_pw.
I hope this can helps you.

Categories