Saturday, 27 October 2018

Using Basic Auth as Middleware PSR-7 PSR-15

TDLR: I'm trying to grasp the idea behind middleware implementation. It appears to be working but how do I properly handle the response so it shows a Basic Auth login prompt to the browser?

--

I'm using:

Running the code below:

$middleware = [
    new \Middlewares\ResponseTime(),
    (new \Middlewares\BasicAuthentication([
        'username1' => 'password1',
        'username2' => 'password2'
    ]))->attribute('username')
];

// Default handler for end of collection
$default = function (\GuzzleHttp\Psr7\ServerRequest $request) {
    // Any implementation of PSR-7 ResponseInterface
    return new \GuzzleHttp\Psr7\Response();
};

$collection = new \Equip\Dispatch\MiddlewareCollection($middleware);

// Any implementation of PSR-7 ServerRequestInterface
$request = \GuzzleHttp\Psr7\ServerRequest::fromGlobals();
$response = $collection->dispatch($request, $default);

print_r($response);

Returns the following:

GuzzleHttp\Psr7\Response Object
(
    [reasonPhrase:GuzzleHttp\Psr7\Response:private] => Unauthorized
    [statusCode:GuzzleHttp\Psr7\Response:private] => 401
    [headers:GuzzleHttp\Psr7\Response:private] => Array
        (
            [WWW-Authenticate] => Array
                (
                    [0] => Basic realm="Login"
                )

            [X-Response-Time] => Array
                (
                    [0] => 16.176ms
                )

        )

    [headerNames:GuzzleHttp\Psr7\Response:private] => Array
        (
            [www-authenticate] => WWW-Authenticate
            [x-response-time] => X-Response-Time
        )

    [protocol:GuzzleHttp\Psr7\Response:private] => 1.1
    [stream:GuzzleHttp\Psr7\Response:private] => 
)

It appears middlewares/response-time and middlewares/http-authentication were executed just fine. However, I am under the impression that middlewares/http-authentication will show an actual login prompt like this:

enter image description here

but it didn't. I am suppose to implement that myself? If yes, how can I do that properly?



from Using Basic Auth as Middleware PSR-7 PSR-15

No comments:

Post a Comment