Skip to content

rcpangeran/slim-basic-auth

 
 

Repository files navigation

Basic Auth Middleware for Slim Build Status

This middleware implements HTTP Basic Authentication for Slim Framework.

Install

You can install the middleware using composer.

{
    "require": {
        "tuupola/slim-basic-auth": "dev-master",
    }
}

Usage

Configuration options are passed as an array. Only mandatory parameter is users. This is an array where you pass one or more "username" => "password" combinations. Username is the key and password is the value.

$app = new \Slim\Slim();

$app->add(new \Slim\Middleware\HttpBasicAuthentication(array(
    "users" => array(
        "root" => "t00r",
        "user" => "passw0rd"
    )
)));

With optional path parameter can authenticate only given part of your website. You can also change the displayed realm using the parameter with same name.

$app = new \Slim\Slim();

$app->add(new \Slim\Middleware\HttpBasicAuthentication(array(
    "path" => "/admin",
    "realm" => "Protected",
    "users" => array(
        "root" => "t00r",
        "user" => "passw0rd"
    )
)));

Custom authentication methods

Sometimes passing users in an array is not enough. To authenticate against custom datasource you can create authenticator class. Authenticator must implement authenticate($user, $pass) method. It must return either true or false.

If you are creating an Enterprise™ software which randomly lets people log in you could use the following.

use \Slim\Middleware\HttpBasicAuthentication\AuthenticatorInterface;

class RandomAuthenticator implements AuthenticatorInterface {
    public function authenticate($user, $pass) {
        return (bool)rand(0,1);
    }
}

$app = new \Slim\Slim();

$app->add(new \Slim\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "realm" => "Protected",
    "authenticator" => new RandomAuthenticator()
]));

Usage with FastCGI

By default Apache does not pass credentials to FastCGI process. If you are using mod_fcgi you can configure authorization headers with:

FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -host 127.0.0.1:9000 -pass-header Authorization

If this is not possible workaround is to pass credentials in an environment variable using mod_rewrite.

RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

The above rewrite rule should work out of the box. In some cases server adds REDIRECT_ prefix to environment name. In this case or if you want to use nonstandard environment use the parameter called environment.

$app = new \Slim\Slim();

$app->add(new \Slim\Middleware\HttpBasicAuthentication(array(
    "path" => "/admin",
    "realm" => "Protected",
    "users" => array(
        "root" => "t00r",
        "user" => "passw0rd"
    ),
    "environment" => "REDIRECT_HTTP_AUTHORIZATION"
)));

About

HTTP Basic Authentication for Slim Framework

Resources

License

Stars

Watchers

Forks

Packages

No packages published