slim-basic-auth icon indicating copy to clipboard operation
slim-basic-auth copied to clipboard

Adding functionality to allow accessing authenticated user outside of…

Open conrad10781 opened this issue 8 years ago • 2 comments

Adding functionality to allow accessing authenticated user outside of superglobal(s).

Currently, the middleware authenticates, but retrieving the authenticated user is still done via $_SERVER["PHP_AUTH_USER"] or $request->getServerParams()["PHP_AUTH_USER"].

There is something unnatural about both, as with any framework you're normally not directly interacting with any of the superglobals, or their variables. IE you access $request->getUri()->getPath() in the application, rather than $_SERVER["REQUEST_URI"] , or $request->getServerParams()["REQUEST_URI"].

With this PR, you will be able to access the authenticated user with $request->getAttribute("authorized_user") in your route, or other middleware ( IE ACL ), and the attribute name is customizable through the existing options, which the README has been updated to provide clarity on.

conrad10781 avatar Dec 13 '17 14:12 conrad10781

Going through unanswered issues and PRs.

This is a good addition and quite common use case. Currently you can do same thing with the before setting.

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

I need to think a bit if the use case is common enough to warrant it's own specific config.

tuupola avatar Dec 22 '18 07:12 tuupola

It's been a while since I originally wrote and submitted this PR. I believe the reason "before" didn't work was that the user wasn't authenticated yet, and in "after" the only thing that worked was returning the $response, so modifying the $request wasn't possible.

The custom authenticator doesn't allow to modify either, so there was an issue with trying to utilize before to set the value, but then trying to revoke it in another part of the middleware if the authentication failed.

Ultimately, my implementation was bit more complicated, but I knew this use case was very common, it was just that the "before" didn't work when using the custom authenticator.

Happy Holidays!

conrad10781 avatar Dec 24 '18 12:12 conrad10781