Skip to content

batrarri/slim-basic-auth

 
 

Repository files navigation

Basic Auth Middleware for Slim

This middleware implements HTTP Basic Authentication for Slim Framework.

Author Software License Build Status HHVM Status Coverage

Install

You can install latest version using composer.

$ composer require tuupola/slim-basic-auth

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([
    "users" => [
        "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([
    "path" => "/admin",
    "realm" => "Protected",
    "users" => [
        "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([
    "path" => "/admin",
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "user" => "passw0rd"
    ],
    "environment" => "REDIRECT_HTTP_AUTHORIZATION"
]));

About

HTTP Basic Authentication for Slim Framework

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 85.9%
  • JavaScript 7.7%
  • Ruby 6.4%