user1897545
user1897545

Reputation: 41

Lumen HTTP Basic Authentication

I am trying to use Laravel's HTTP Basic Authentication in a Lumen project.

On the routes.php file, I set the auth.basic middleware for the rout I need to authenticate:

$app->get('/test', ['middleware' => 'auth.basic', function() {
    return "test stuff";
}]);

On bootstrap.php I have registered the middleware and the auth service provider:

$app->routeMiddleware([
    'auth.basic' =>  Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
]);

[...]

$app->register(App\Providers\AuthServiceProvider::class);

But when I try to test the route by visiting http://lumen/test I get the following error:

Fatal error: Call to undefined method Illuminate\Auth\RequestGuard::basic() in C:\source\lumen\vendor\illuminate\auth\Middleware\AuthenticateWithBasicAuth.php on line 38

Does anyone know how can I get the code of the guard for basic authentication?

Thanks.

Upvotes: 3

Views: 2589

Answers (1)

Nikolaj Boel Jensen
Nikolaj Boel Jensen

Reputation: 103

Ran into a similar problem, wanted to use basic auth for users in the database, so ended up writing my own AuthServiceProvider and registered that in bootstrap/app.php

Here is the class, maybe it will help you in your case.

<?php

namespace App\Providers;

use App\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\ServiceProvider;

class HttpBasicAuthServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Boot the authentication services for the application.
     *
     * @return void
     */
    public function boot()
    {
        $this->app['auth']->viaRequest('api', function ($request) {
            $email = $_SERVER['PHP_AUTH_USER'];
            $password = $_SERVER['PHP_AUTH_PW'];

            if ($email && $password) {
                $user = User::whereEmail($email)->first();
                if (Hash::check($password, $user->password)) {
                    return $user;
                }
            }

            return null;
        });
    }
}

Upvotes: 1

Related Questions