【问题标题】:Lumen HTTP Basic Authentication without use of database不使用数据库的 Lumen HTTP 基本身份验证
【发布时间】:2016-03-30 19:30:27
【问题描述】:

我正在使用 Lumen 创建一个 RESTful API,并希望添加 HTTP 基本身份验证以确保安全。

routes.php 文件中,它为每条路由设置了auth.basic 中间:

$app->get('profile', ['middleware' => 'auth.basic', function() {
     // logic here
}]);

现在,当我访问http://example-api.local/profile 时,系统会提示我进行 HTTP 基本身份验证,这很好。但是当我尝试登录时,我收到此错误消息:Fatal error: Class '\App\User' not found in C:\..\vendor\illuminate\auth\EloquentUserProvider.php on line 126

我不希望在数据库上完成用户验证,因为我只有一个凭据,所以很可能它只会获取变量上的用户名和密码并从那里验证它。

顺便说一句,我通过laracast tutorial 引用它。虽然这是一个 Laravel 应用教程,但我正在 Lumen 应用上实现它。

【问题讨论】:

    标签: php laravel authentication basic-authentication lumen


    【解决方案1】:

    我正在回答我自己的问题,因为我能够让它发挥作用,但仍然想了解其他人关于我的解决方案和正确的 laravel 方法的更多见解。

    我能够通过创建执行此操作的自定义中间件来解决此问题:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class HttpBasicAuth
    {
    
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $envs = [
                'staging',
                'production'
            ];
    
            if(in_array(app()->environment(), $envs)) {
                if($request->getUser() != env('API_USERNAME') || $request->getPassword() != env('API_PASSWORD')) {
                    $headers = array('WWW-Authenticate' => 'Basic');
                    return response('Unauthorized', 401, $headers);
                }
            }
    
            return $next($request);
        }
    
    }
    

    如果您查看代码,它非常基本并且运行良好。虽然我想知道是否有一种“Laravel”方式来执行此操作,因为上面的代码是执行 HTTP 基本身份验证的纯 PHP 代码。

    如果您注意到,用户名和密码的验证是硬编码在 .env 文件中的,因为我认为不需要访问数据库进行验证。

    【讨论】:

    • 这很好用。唯一的问题(非常重要)是这条线:if($request-&gt;getUser() != env('API_USERNAME') &amp;&amp; $request-&gt;getPassword() != env('API_PASSWORD')) { 应该是 if($request-&gt;getUser() != env('API_USERNAME') || $request-&gt;getPassword() != env('API_PASSWORD')) { - 注意 ||&amp;&amp;
    • 非常好的简单解决方案。进一步清理它的一种方法是将环境条件更改为:app()-&gt;environment('production', 'staging')
    • 不错的解决方案!感谢分享!在 Lumen 5.1 上为我工作。
    【解决方案2】:

    检查您的bootstrap/app.php。确保您已注册您的 auth.basic 中间件,如下所示:

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

    之后,改变你的路线:

    $app->get('/profile', ['middleware' => 'auth.basic', function() {
        // Logic
    }]);
    

    编辑

    如果你想使用database而不是eloquent认证,你可以调用:

    Auth::setDefaultDriver('database');
    

    在您尝试进行身份验证之前:

    Auth::attempt([
        'email' => 'info@foo.bar',
        'password' => 'secret',
    ]);
    

    编辑#2

    如果您希望以硬编码方式进行身份验证,您可以为AuthManager 类定义自己的驱动程序:

    Auth::setDefaultDriver('basic');
    
    Auth::extend('basic', function () {
        return new App\Auth\Basic();
    });
    

    然后下面是App\Auth\Basic类的基础:

    <?php
    
    namespace App\Auth;
    
    use Illuminate\Contracts\Auth\UserProvider;
    use Illuminate\Contracts\Auth\Authenticatable;
    
    class Basic implements UserProvider
    {
        /**
         * Retrieve a user by their unique identifier.
         *
         * @param  mixed  $identifier
         * @return \Illuminate\Contracts\Auth\Authenticatable|null
         */
        public function retrieveById($identifier)
        {
    
        }
    
        /**
         * Retrieve a user by their unique identifier and "remember me" token.
         *
         * @param  mixed   $identifier
         * @param  string  $token
         * @return \Illuminate\Contracts\Auth\Authenticatable|null
         */
        public function retrieveByToken($identifier, $token)
        {
    
        }
    
        /**
         * Update the "remember me" token for the given user in storage.
         *
         * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
         * @param  string  $token
         * @return void
         */
        public function updateRememberToken(Authenticatable $user, $token)
        {
    
        }
    
        /**
         * Retrieve a user by the given credentials.
         *
         * @param  array  $credentials
         * @return \Illuminate\Contracts\Auth\Authenticatable|null
         */
        public function retrieveByCredentials(array $credentials)
        {
            return new User($credentials);
        }
    
        /**
         * Validate a user against the given credentials.
         *
         * @param  \Illuminate\Contracts\Auth\Authenticatable  $user
         * @param  array  $credentials
         * @return bool
         */
        public function validateCredentials(Authenticatable $user, array $credentials)
        {
            $identifier = $user->getAuthIdentifier();
            $password = $user->getAuthPassword();
    
            return ($identifier === 'info@foobarinc.com' && $password === 'password');
        }
    }
    

    注意validateCredentials方法需要的第一个参数是Illuminate\Contracts\Auth\Authenticatable接口的实现,所以你需要创建自己的User类:

    <?php
    
    namespace App\Auth;
    
    use Illuminate\Support\Fluent;
    use Illuminate\Contracts\Auth\Authenticatable;
    
    class User extends Fluent implements Authenticatable
    {
        /**
         * Get the unique identifier for the user.
         *
         * @return mixed
         */
        public function getAuthIdentifier()
        {
            return $this->email;
        }
    
        /**
         * Get the password for the user.
         *
         * @return string
         */
        public function getAuthPassword()
        {
            return $this->password;
        }
    
        /**
         * Get the token value for the "remember me" session.
         *
         * @return string
         */
        public function getRememberToken()
        {
    
        }
    
        /**
         * Set the token value for the "remember me" session.
         *
         * @param  string  $value
         * @return void
         */
        public function setRememberToken($value)
        {
    
        }
    
        /**
         * Get the column name for the "remember me" token.
         *
         * @return string
         */
        public function getRememberTokenName()
        {
    
        }
    }
    

    你可以通过Auth::attempt方法测试你自己的驱动:

    Auth::setDefaultDriver('basic');
    
    Auth::extend('basic', function () {
        return new App\Auth\Basic();
    });
    
    dd(Auth::attempt([
        'email' => 'info@foobarinc.com',
        'password' => 'password',
    ])); // return true
    

    【讨论】:

    • 我对 auth 中间件加载没有任何问题,问题是它正在验证用户表中的用户。我不希望它从数据库验证身份验证,因为它只有一个用于验证和连接到数据库的凭据,只有一条记录对我来说似乎意义不大。那么为什么不直接创建一个$user == 'John' 呢?我可以通过 PHP 的 HTTP 身份验证来做到这一点,但我想知道是否有“Laravel”方式来做到这一点。
    • 刚刚使用 Laravel 5.8。我需要使用Auth::provider 而不是Auth::extend。而且Authenticatable接口也需要getAuthIdentifierName方法(empty好像也行)。
    • 如果有人使用此代码,请注意&amp;&amp; $password = 'password'(我会修复作者的答案)。
    【解决方案3】:

    首先,我们将在中间件中扩展 AuthenticateWithBasicAuth。

    <?php
    
     namespace App\Http\Middleware;
     use \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth;
    
    
     class HttpBasicAuth extends AuthenticateWithBasicAuth
     {
    
     }
    

    在 config/auth.php 创建自定义保护,我们将使用 custom_http_guard 和 HttpBasicAuth。

    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver' => 'token',
            'provider' => 'users',
        ],
    
        'custom_http_guard' => [
            'driver' => 'token',
            'provider' => 'custom_http_provider',
        ],
    ],
    

    我们将使用 Laravel 的默认 'token' 驱动程序。

    'providers' => [
        'users' => [
            'driver' => 'eloquent',
            'model' => App\User::class,
        ],
    
     'custom_http_provider' => [
         'data' => [
             'email' => 'info@foo.bar',
             'password' => 'secret',
          ]
     ],
    ],
    

    如果你能找到像上面那样返回数据的方法。那么你就可以按照 laravel 标准摇滚并获取代码了。

    希望你明白了! 寻找最终解决方案。如果有人可以完成:)

    外婆阿罗拉

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-14
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 2014-01-22
      • 2021-03-21
      • 2011-11-12
      • 2011-05-05
      相关资源
      最近更新 更多