Lumen HTTP基本身份验证

3

我正在尝试在Lumen项目中使用Laravel的HTTP基本身份验证。

routes.php文件中,我为需要进行身份验证的路由设置了auth.basic中间件:

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

bootstrap.php 中,我已经注册了中间件和认证服务提供程序:

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

[...]

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

但是当我尝试通过访问http://lumen/test来测试路由时,我收到了以下错误信息: Fatal error: Call to undefined method Illuminate\Auth\RequestGuard::basic() in C:\source\lumen\vendor\illuminate\auth\Middleware\AuthenticateWithBasicAuth.php on line 38 有人知道如何获取基本认证的守卫代码吗?
谢谢。
1个回答

1
遇到了类似的问题,想要在数据库中使用基本身份验证,所以最终编写了自己的 AuthServiceProvider 并在 bootstrap/app.php 中注册。
以下是该类,希望能对你有所帮助。
<?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;
        });
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接