php - Laravel 5.4 无需数据库的基本身份验证

标签 php laravel authentication basic-authentication laravel-5.4

问题:我需要在使用 Laravel 5.4 创建的 API 上实现基本身份验证。由于我们需要在没有数据库的情况下实现它(只需从 config() 获取凭据),我尝试创建一个注册的中间件,如下所示:

<?php

namespace App\Http\Middleware;

class AuthenticateOnceWithBasicAuth
{
    public function handle($request, $next)
    {
        if($request->getUser() != conf('auth.credentials.user') && $request->getPassword() != conf('auth.credentials.pass')) {
            $headers = array('WWW-Authenticate' => 'Basic');
            return response('Unauthorized', 401, $headers);
        }
        return $next($request);
    }
}

它可以工作,但这样我只能拥有整个 API 的一个凭据。 我尝试在配置中创建多个凭据,从请求中保存用户和密码,但这样一来,它就像禁用了基本身份验证一样。

问题:有什么办法可以实现这一点吗?如何在不使用数据库的情况下在配置文件中拥有多个凭据?

最佳答案

您可以将授权的用户名和密码作为集合保存在配置文件中。

config/myconfig.php

return [
        'authorized_identities' => collect([
             ['user1','password1'],
             ['user2','password2'],
             ...
        ]),
];

然后在你的中间件中

if(config('myconfig.authorized_identites')->contains([$request->getUser(),$request->getPassword()]))

关于php - Laravel 5.4 无需数据库的基本身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43981643/

相关文章:

php - 使用javascript中的get将数据发送到iframe

javascript - chrome onAuthRequired 不触发

php - Kafka - 如何监视新消息

php - 在多维数组中搜索键并返回它的路径

facebook - laravel4 hybridauth facebook 身份验证失败! Facebook 返回了无效的用户 ID

php - Laravel 4 在 Controller 中注入(inject) Eloquent 模型

laravel - 我应该如何在 Laravel 包中输入提示 UserModel?

django - 自定义用户类会破坏 django 中的应用程序吗?

Java MD5 哪一个是正确的?

php - 如果值为真,则应选中复选框