不使用数据库的 Lumen HTTP 基本身份验证

Lumen HTTP Basic Authentication without use of database

我正在使用 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 应用程序上实现它。

检查你的 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');

在您尝试验证之前:[​​=28=]

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

编辑#2

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

Auth::setDefaultDriver('basic');

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

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

<?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 class:

<?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

我正在回答我自己的问题,因为我能够让它发挥作用,但仍然想从其他人那里了解更多关于我的解决方案和正确的 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 文件中的,因为我认为验证不需要访问数据库。

首先我们将在中间件中扩展 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',
      ]
 ],
],

如果你能找到像 above.Then 这样的 return 数据的方法,你就会摇滚并获得遵循 laravel 标准的代码。

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

Vaibhav 阿罗拉