How to use Basic Auth on OVH with CakePHP

Tutorial

This topic is intended for advanced users who are familiar with PHP's HTTP authentication functions, and who want to password protect a PHP file, then find out the username and password that the visitor provided so they can be used in the PHP script.

We use the CGI version of PHP for added security, so you can't normally use the "PHP_AUTH_USER" and "PHP_AUTH_PW" variables. However, there is a way to "trick" Apache and PHP into doing this. Just follow the instructions below.

1.In your .htaccess

First of all, create a .htaccess file in the same directory as your PHP script. The file should contain these lines:

SetEnv PHP_VER 5.4
SetEnvIf Authorization "(.*)" HTTP_AUTHORIZATION=$1

Options +FollowSymLinks
RewriteEngine on
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteRule ^$ app/webroot/ [L]
RewriteRule (.*) app/webroot/$1 [L]


2. In your AppController.php

In the PHP script, include this code before using the PHP_AUTH_USER or PHP_AUTH_PW variables:


public function beforeFilter(){
if (preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches))
{
list($name, $password) = explode(':', base64_decode($matches[1]));
$_SERVER['PHP_AUTH_USER'] = strip_tags($name);
$_SERVER['PHP_AUTH_PW'] = strip_tags($password);
}
$this->Auth->allow();
}

That allows PHP to use the HTTP_AUTHORIZATION variable to extract the PHP_AUTH_USER andPHP_AUTH_PW variables.

3. In your file where you do the login (I use mail as username)

public function beforeFilter() {
parent::beforeFilter();

$this->Auth->allow('login');

$this->Auth->authenticate = array(
'Basic' => array(
'fields' => array('username' => 'mail'),
'scope' => array(
'User.active' => true)));

}

If you get some problems, contact me at [email protected]