Skip to content

Instantly share code, notes, and snippets.

@akkunchoi
Created November 8, 2013 03:36
Show Gist options
  • Select an option

  • Save akkunchoi/7365923 to your computer and use it in GitHub Desktop.

Select an option

Save akkunchoi/7365923 to your computer and use it in GitHub Desktop.
This is a Slim middleware that provides http basic authentication.
<?php
/**
* This is a Slim middleware that provides http basic authentication.
*
* usage:
*
* $app->add(new HttpBasicAuth(array(
* 'users' => array('username' => 'password'),
* 'when' => function(\Slim\Http\Request $req, $res){
* return $req->getPathInfo() === '/admin';
* }
* )));
*
* Ref. http://www.9bitstudios.com/2013/06/basic-http-authentication-with-the-slim-php-framework-rest-api/
*/
class HttpBasicAuth extends \Slim\Middleware
{
/**
* @var array
*/
protected $options;
/**
* Constructor
*
* @param string $options The HTTP Authentication realm
*/
public function __construct($options = array())
{
$defaults = array('realm' => 'Protected Area');
if (is_string($options)){
$options = array('realm' => $options);
}
$options = array_merge($defaults, $options);
$this->options = $options;
}
/**
* Deny Access
*
*/
public function deny_access() {
$res = $this->app->response();
$res->status(401);
$res->header('WWW-Authenticate', sprintf('Basic realm="%s"', $this->options['realm']));
}
/**
* Authenticate
*
* @param string $username The HTTP Authentication username
* @param string $password The HTTP Authentication password
*
*/
public function authenticate($username, $password) {
if(!ctype_alnum($username))
return false;
if(isset($username) && isset($password)) {
$users = $this->options['users'];
if (isset($users[$username])){
if ($users[$username] === $password){
return true;
}
}
return false;
}
else
return false;
}
/**
* Call
*
* This method will check the HTTP request headers for previous authentication. If
* the request has already authenticated, the next middleware is called. Otherwise,
* a 401 Authentication Required response is returned to the client.
*/
public function call()
{
$req = $this->app->request();
$res = $this->app->response();
if (isset($this->options['when']) && is_callable($this->options['when'])){
if (false === call_user_func_array($this->options['when'], array($req, $res))){
return $this->next->call();
}
}
$authUser = $req->headers('PHP_AUTH_USER');
$authPass = $req->headers('PHP_AUTH_PW');
if ($this->authenticate($authUser, $authPass)) {
$this->next->call();
} else {
$this->deny_access();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment