PHPackages                             tuupola/slim-basic-auth - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. tuupola/slim-basic-auth

ActiveLibrary[HTTP &amp; Networking](/categories/http)

tuupola/slim-basic-auth
=======================

PSR-7 and PSR-15 HTTP Basic Authentication Middleware

3.4.0(1y ago)4442.0M—2.4%66[7 issues](https://github.com/tuupola/slim-basic-auth/issues)[2 PRs](https://github.com/tuupola/slim-basic-auth/pulls)20MITPHPPHP ^7.2|^8.0

Since May 23Pushed 1y ago16 watchersCompare

[ Source](https://github.com/tuupola/slim-basic-auth)[ Packagist](https://packagist.org/packages/tuupola/slim-basic-auth)[ Docs](https://appelsiini.net/projects/slim-basic-auth)[ RSS](/packages/tuupola-slim-basic-auth/feed)WikiDiscussions 3.x Synced 1mo ago

READMEChangelogDependencies (11)Versions (45)Used By (20)

PSR-7 and PSR-15 Basic Auth Middleware
======================================

[](#psr-7-and-psr-15-basic-auth-middleware)

This middleware implements [HTTP Basic Authentication](https://en.wikipedia.org/wiki/Basic_access_authentication). It was originally developed for Slim but can be used with all frameworks using PSR-7 or PSR-15 style middlewares. It has been tested with [Slim Framework](http://www.slimframework.com/) and [Zend Expressive](https://zendframework.github.io/zend-expressive/).

[![Latest Version](https://camo.githubusercontent.com/8be5bd93b27091b2599f5f06de1a3a80b44fc2b5777e3ccdb9b59bca5709416b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f747575706f6c612f736c696d2d62617369632d617574682e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/tuupola/slim-basic-auth)[![Packagist](https://camo.githubusercontent.com/f0109d508699472c6c247ed639a8c3d81566924ce683254823452288134debd9/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f747575706f6c612f736c696d2d62617369632d617574682e737667)](https://packagist.org/packages/tuupola/slim-basic-auth)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE)[![Build Status](https://camo.githubusercontent.com/f12c20d8e070825d3b354ea324e3386bed062379af388009eeb919cacf4f9562/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f747575706f6c612f736c696d2d62617369632d617574682f74657374732e796d6c3f6272616e63683d332e78267374796c653d666c61742d737175617265)](https://github.com/tuupola/slim-basic-auth/actions)[![Coverage](https://camo.githubusercontent.com/3aa45c1d2890b74a59871be4d76fb5ae7865d5b5e0e7a31c38cacac6de6c7c87/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f747575706f6c612f736c696d2d62617369632d617574682f332e782e7376673f7374796c653d666c61742d737175617265)](https://codecov.io/gh/tuupola/slim-basic-auth/branch/3.x)

Heads up! You are reading documentation for [3.x branch](https://github.com/tuupola/slim-basic-auth/tree/3.x) which is PHP 7.1 and up only. If you are using older version of PHP see the [2.x branch](https://github.com/tuupola/slim-basic-auth/tree/2.x). These two branches are not backwards compatible, see [UPGRADING](https://github.com/tuupola/slim-basic-auth/blob/3.x/UPGRADING.md) for instructions how to upgrade.

Install
-------

[](#install)

Install latest version using [composer](https://getcomposer.org/).

```
$ composer require tuupola/slim-basic-auth

```

Usage
-----

[](#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\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ]
]));
```

Same with Zend Expressive.

```
$app = Zend\Expressive\AppFactory::create();

$app->pipe(new Tuupola\Middleware\HttpBasicAuthentication([
    "users" => [
        "root" => "t00r",
        "user" => "passw0rd"
    ]
]));
```

Rest of the examples assume you are using Slim Framework.

Cleartext passwords are only good for quick testing. You probably want to use hashed passwords. Hashed password can be generated with `htpasswd` command line tool or [password\_hash()](http://php.net/manual/en/function.password-hash.php) PHP function

```
$ htpasswd -nbBC 10 root t00r
root:$2y$10$1lwCIlqktFZwEBIppL4ak.I1AHxjoKy9stLnbedwVMrt92aGz82.O
$ htpasswd -nbBC 10 somebody passw0rd
somebody:$2y$10$6/vGXuMUoRlJUeDN.bUWduge4GhQbgPkm6pfyGxwgEWT0vEkHKBUW

```

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "users" => [
        "root" => '$2y$10$1lwCIlqktFZwEBIppL4ak.I1AHxjoKy9stLnbedwVMrt92aGz82.O',
        "somebody" => '$2y$10$6/vGXuMUoRlJUeDN.bUWduge4GhQbgPkm6pfyGxwgEWT0vEkHKBUW'
    ]
]));
```

Even if you are using hashed passwords it is not the best idea to store credentials in the code. Instead you could store them in environment or external file which is not committed to GitHub.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "users" => [
        "admin" => getenv("ADMIN_PASSWORD")
    ]
]));
```

Optional parameters
-------------------

[](#optional-parameters)

### Path

[](#path)

The optional `path` parameter allows you to specify the protected part of your website. It can be either a string or an array. You do not need to specify each URL. Instead think of `path` setting as a folder. In the example below everything starting with `/api` will be authenticated.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/api", /* or ["/admin", "/api"] */
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ]
]));
```

### Ignore

[](#ignore)

With optional `ignore` parameter you can make exceptions to `path` parameter. In the example below everything starting with `/api` and `/admin` will be authenticated with the exception of `/api/token` and `/admin/ping` which will not be authenticated.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => ["/api", "/admin"],
    "ignore" => ["/api/token", "/admin/ping"],
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ]
]));
```

### Before

[](#before)

Before function is called only when authentication succeeds but before the next incoming middleware is called. You can use this to alter the request before passing it to the next incoming middleware in the stack. If it returns anything else than `\Psr\Http\Message\RequestInterface` the return value will be ignored.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ],
    "before" => function ($request, $arguments) {
        return $request->withAttribute("user", $arguments["user"]);
    }
]));
```

### After

[](#after)

After function is called only when authentication succeeds and after the incoming middleware stack has been called. You can use this to alter the response before passing it next outgoing middleware in the stack. If it returns anything else than `\Psr\Http\Message\ResponseInterface` the return value will be ignored.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ],
    "after" => function ($response, $arguments) {
        return $response->withHeader("X-Brawndo", "plants crave");
    }
]));
```

Security
--------

[](#security)

Basic authentication transmits credentials in clear text. For this reason HTTPS should always be used together with basic authentication. If the middleware detects insecure usage over HTTP it will throw a `RuntimeException` with the following message: `Insecure use of middleware over HTTP denied by configuration`.

By default, localhost is allowed to use HTTP. The security behavior of `HttpBasicAuthentication` can also be configured to allow:

- [a whitelist of domains to connect insecurely](#how-to-configure-a-whitelist)
- [forwarding of an HTTPS connection to HTTP](#allow-https-termination-and-forwarding)
- [all unencrypted traffic](#allow-all-unencrypted-traffic)

### How to configure a whitelist:

[](#how-to-configure-a-whitelist)

You can list hosts to allow access insecurely. For example, to allow HTTP traffic to your development host `dev.example.com`, add the hostname to the `relaxed` config key.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "secure" => true,
    "relaxed" => ["localhost", "dev.example.com"],
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ]
]));
```

### Allow HTTPS termination and forwarding

[](#allow-https-termination-and-forwarding)

If public traffic terminates SSL on a load balancer or proxy and forwards to the application host insecurely, `HttpBasicAuthentication` can inspect request headers to ensure that the original client request was initiated securely. To enable, add the string `headers` to the `relaxed` config key.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "secure" => true,
    "relaxed" => ["localhost", "headers"],
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ]
]));
```

### Allow all unencrypted traffic

[](#allow-all-unencrypted-traffic)

To allow insecure usage by any host, you must enable it manually by setting `secure` to `false`. This is generally a bad idea. Use only if you know what you are doing.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "secure" => false,
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ]
]));
```

Custom authentication methods
-----------------------------

[](#custom-authentication-methods)

Sometimes passing users in an array is not enough. To authenticate against custom datasource you can pass a callable as `authenticator` parameter. This can be either a class which implements AuthenticatorInterface or anonymous function. Callable receives an array containing `user` and `password` as argument. In both cases authenticator 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 Tuupola\Middleware\HttpBasicAuthentication\AuthenticatorInterface;
use Tuupola\Middleware\HttpBasicAuthentication;

class RandomAuthenticator implements AuthenticatorInterface {
    public function __invoke(array $arguments): bool {
        return (bool)rand(0,1);
    }
}

$app = new Slim\App;

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

Same thing can also be accomplished with anonymous function.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "realm" => "Protected",
    "authenticator" => function ($arguments) {
        return (bool)rand(0,1);
    }
]));
```

Setting response body when authentication fails
-----------------------------------------------

[](#setting-response-body-when-authentication-fails)

By default plugin returns an empty response body with 401 response. You can return custom body using by providing an error handler. This is useful for example when you need additional information why authentication failed.

```
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/api",
    "realm" => "Protected",
    "users" => [
        "root" => "t00r",
        "somebody" => "passw0rd"
    ],
    "error" => function ($response, $arguments) {
        $data = [];
        $data["status"] = "error";
        $data["message"] = $arguments["message"];

        $body = $response->getBody();
        $body->write(json_encode($data, JSON_UNESCAPED_SLASHES));

        return $response->withBody($body);
    }
]));
```

Usage with PDO
--------------

[](#usage-with-pdo)

For those in hurry there is a ready made PDO authenticator. It covers most of the use cases. You probably end up implementing your own though.

```
use Tuupola\Middleware\HttpBasicAuthentication\PdoAuthenticator;

$pdo = new PDO("sqlite:/tmp/users.sqlite");
$app = new Slim\App;

$app->add(new Tuupola\Middleware\HttpBasicAuthentication([
    "path" => "/admin",
    "realm" => "Protected",
    "authenticator" => new PdoAuthenticator([
        "pdo" => $pdo
    ])
]));
```

For better explanation see [Basic Authentication from Database](http://www.appelsiini.net/2014/slim-database-basic-authentication) blog post.

Usage with FastCGI
------------------

[](#usage-with-fastcgi)

By default Apache [does not pass credentials](https://bugs.php.net/bug.php?id=35752) 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

```

Testing
-------

[](#testing)

You can run tests either manually or automatically on every code change. Automatic tests require [entr](http://entrproject.org/) to work.

```
$ make test
```

```
$ brew install entr
$ make watch
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/tuupola/slim-basic-auth/blob/3.x/CONTRIBUTING.md) for details.

Security
--------

[](#security-1)

If you discover any security related issues, please email  instead of using the issue tracker.

License
-------

[](#license)

The MIT License (MIT). Please see [LICENSE](https://github.com/tuupola/slim-basic-auth/blob/3.x/LICENSE) for more information.

###  Health Score

57

—

FairBetter than 98% of packages

Maintenance36

Infrequent updates — may be unmaintained

Popularity61

Solid adoption and visibility

Community38

Small or concentrated contributor base

Maturity81

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 95.9% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~92 days

Recently: every ~393 days

Total

42

Last Release

595d ago

Major Versions

1.0.0 → 2.0.02015-12-10

1.0.1 → 2.2.22017-02-27

1.0.2 → 3.0.0-rc.12017-04-26

2.3.0 → 3.0.0-rc.32017-12-03

2.x-dev → 4.x-dev2020-06-10

PHP version history (6 changes)0.5.0PHP &gt;=5.3.0

2.1.1PHP ^5.5 || ^7.0

3.0.0-rc.3PHP ^7.0

3.0.0-rc.5PHP ^7.1

3.3.0PHP ^7.1|^8.0

3.x-devPHP ^7.2|^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/3325405a7d8a43bc40dd0e760a4b7f268fba32a7150cf0327f64f13d1661df0b?d=identicon)[tuupola](/maintainers/tuupola)

---

Top Contributors

[![tuupola](https://avatars.githubusercontent.com/u/21913?v=4)](https://github.com/tuupola "tuupola (305 commits)")[![piotr-cz](https://avatars.githubusercontent.com/u/612953?v=4)](https://github.com/piotr-cz "piotr-cz (2 commits)")[![twish](https://avatars.githubusercontent.com/u/5931183?v=4)](https://github.com/twish "twish (2 commits)")[![acinader](https://avatars.githubusercontent.com/u/700572?v=4)](https://github.com/acinader "acinader (2 commits)")[![Ducatel](https://avatars.githubusercontent.com/u/1184332?v=4)](https://github.com/Ducatel "Ducatel (2 commits)")[![vool](https://avatars.githubusercontent.com/u/441840?v=4)](https://github.com/vool "vool (1 commits)")[![jankonas](https://avatars.githubusercontent.com/u/7345659?v=4)](https://github.com/jankonas "jankonas (1 commits)")[![mustikkakeitto](https://avatars.githubusercontent.com/u/1962612?v=4)](https://github.com/mustikkakeitto "mustikkakeitto (1 commits)")[![urlund](https://avatars.githubusercontent.com/u/376721?v=4)](https://github.com/urlund "urlund (1 commits)")[![3ace](https://avatars.githubusercontent.com/u/509131?v=4)](https://github.com/3ace "3ace (1 commits)")

---

Tags

authenticationmiddlewarephppsr-15psr-7psr-7middlewareauthpsr-15

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Rector

Code StyleECS

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tuupola-slim-basic-auth/health.svg)

```
[![Health](https://phpackages.com/badges/tuupola-slim-basic-auth/health.svg)](https://phpackages.com/packages/tuupola-slim-basic-auth)
```

###  Alternatives

[tuupola/cors-middleware

PSR-7 and PSR-15 CORS middleware

1331.8M24](/packages/tuupola-cors-middleware)[mezzio/mezzio

PSR-15 Middleware Microframework

3883.6M97](/packages/mezzio-mezzio)[relay/relay

A PSR-15 server request handler.

3302.1M86](/packages/relay-relay)[jimtools/jwt-auth

PSR-15 JWT Authentication middleware, A replacement for tuupola/slim-jwt-auth

20142.3k3](/packages/jimtools-jwt-auth)[hkarlstrom/openapi-validation-middleware

PSR-7 and PSR-15 OpenAPI Validation Middleware

95198.8k1](/packages/hkarlstrom-openapi-validation-middleware)[laminas/laminas-stratigility

PSR-7 middleware foundation for building and dispatching middleware pipelines

586.6M81](/packages/laminas-laminas-stratigility)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
