[eluser]eilrahc[/eluser]
Hi everyone,
I needed a very minimal authentication setup for one controller but found that the existing CI auth libraries were either way overkill, a bit ugly, or not maintained. After some trial and error, I came up with the below. HTTP Basic authentication is performed in the controller and the requested method (e.g., index) is not actually executed unless auth was successful. Since my HTTP/PHP/CI is a little rusty, I was wondering if the experts out there would mind taking a quick look at it and let me (and more important, the community) know what drawbacks might be lurking here.
(One that I know of: the username/password should not be stored in plaintext in the controller itself. This was done only for demonstration purposes. And obviously the whole thing should be behind HTTPS.)
Thanks!
Code:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Authtest extends Controller {
private $admin_user = 'admin';
private $admin_pw = 'foobar';
private function _send_auth_headers() {
header('HTTP/1.0 401 Unauthorized');
header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Moderation Authentication"');
}
public function __construct() {
parent::Controller();
$this->load->helper(array('url'));
$authenticated = false;
$auth_user = $this->input->server('PHP_AUTH_USER');
$auth_pw = $this->input->server('PHP_AUTH_PW');
if (empty($auth_user)) {
$this->_send_auth_headers();
die('Authentication failed.');
}
if ($auth_user == $this->admin_user && $auth_pw == $this->admin_pw) {
$authenticated = true;
} else {
$this->_send_auth_headers();
}
if ( ! $authenticated) {
die('Invalid username or password');
}
}
// This, and any other methods, will only be executed upon positive
// authentication.
public function index() {
echo "Authentication sucessful.";
}
}
/* End of file authtest.php */
/* Location: ./system/application/controllers/authtest.php */