How to add basic authentication to slim project
How to add basic authentication to slim project
Today I show you how to add basic authentication to slim project. I used it in my Slim project "Image optimizer API".
I wanted use OAuth 2, but I decided that I don’t need it. OAuth 2 is to complicate to my project and basic authentication have exactly that what I need to secure my API.
To implement basic authentication need you a library "PSR-7 Basic Auth Middleware". You can easy install it using composer:
composer require tuupola/slim-basic-auth
I use database to save users access data, so I used PdoAuthenticator in bootstrap.app:
use \Slim\Middleware\HttpBasicAuthentication\PdoAuthenticator;
In this same file I added configuration:
$app->add(new \Slim\Middleware\HttpBasicAuthentication([ "authenticator" => new PdoAuthenticator([ "pdo" => $pdo, "table" => "users", "user" => "name", "hash" => "password" ]), "path" => "/api", "realm" => "Protected", "secure" => false, "error" => function ($request, $response, $arguments) { $data = []; $data["status"] = "error"; $data["message"] = $arguments["message"]; return $response->write(json_encode($data, JSON_UNESCAPED_SLASHES)); } ]));
As you can see, I use basic authentication in path “/api”. I used “secure => false” to tests on the local server, but on production server, I will use https.
I decelerated $pdo variable in bootstrap/database.php file.
I moved Csrf Middleware from bootstrap/app.php to route.php because now I don’t need it in any sites.
I added in this same file a new path:
$app->post('/api', 'ImageController:compressImage');
At end I add a new Apache rule to public/.htaccess:
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
From now when user send the request to “/api”, must add username and password to header too.
1 Comment
Don’t use Basic auth at all, ever. It is insecure.