pflorek/php-basic-auth

Provides a simple way to get or set credentials (username, password) on a PSR-7 `RequestInterface`. Also it helps challenging an unauthorized client by adding the 'WWW-authenticate' header line with status code 401 to a PSR-7 `ResponseInterface`.

1.0.1 2018-11-16 00:00 UTC

This package is auto-updated.

Last update: 2024-11-17 09:53:41 UTC


README

Build Status Coverage Status Scrutinizer Code Quality Latest Stable Version Total Downloads Latest Unstable Version License Monthly Downloads Daily Downloads composer.lock

This library provides a simple way to get or set credentials (username, password) on a PSR-7 RequestInterface. Also it helps challenging an unauthorized client by adding the 'WWW-authenticate' header line with status code 401 to a PSR-7 ResponseInterface. It should be helpful if a PSR-15 Middleware is not applicable.

  • There is no validation if username is correct (should not contain :).
  • Also there is no validation if basic credentials are properly base64 encoded.
  • Omitted Authorization header line or missing basic credentials will return null credentials.
  • Can only challenge for Basic Auth. Digest is currently not supported.
  • For backward compatibility for PHP >= 5.4 PSR-17 HTTP factories currently not supported.
  • Should comply with RFC 7617.

Usage

Obtain credentials

Obtain credentials (username, password) from PSR-7 request interface.

use Psr\Http\Message\RequestInterface;
use \PFlorek\BasicAuth\BasicAuth;

//Given request with header line 'Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='
$credentials = $this->basicAuth->obtainCredentials($request);

var_dump($credentials);

//object(Credentials)#1 (2) {
//  ["username":"Credentials":private]=>
//  string(7) "Aladdin"
//  ["password":"Credentials":private]=>
//  string(11) "open sesame"
//}

Add credentials

Add credentials (username, password) to PSR-7 request interface for basic authentication.

use Psr\Http\Message\RequestInterface;
use \PFlorek\BasicAuth\BasicAuth;

$credentials = new Credentials('Alladin, 'open sesame');
$request = $this->basicAuth->addCredentials($request, $credentials);

var_dump($request->getHeaderLine('WWW-Authenticate'));

//string(34) "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="

Add challenge

Add challenge with realm to PSR-7 response interface for basic authentication.

use Psr\Http\Message\ResponseInterface;
use \PFlorek\BasicAuth\BasicAuth;

$response = $this->basicAuth->addChallenge($response, 'WallyWorld);

var_dump($response->getHeaderLine('WWW-Authenticate'));

//string(24) "Basic realm=\"WallyWorld\""

var_dump($response->getStatusCode());

//int(401)

Installation

Use Composer to install the package:

composer require pflorek/php-basic-auth

Authors

Contribute

Contributions are always welcome!

License

All contents of this package are licensed under the MIT license.