doufei4418 2015-12-24 10:29
浏览 81
已采纳

流明的HTTP基本身份验证,不使用数据库

I'm creating a RESTful API using Lumen and would like to add HTTP basic Authentication for security.

On the routes.php file, it set the auth.basic middle for every routes:

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

Now when I access http://example-api.local/profile I am now prompted with the HTTP basic authentication, which is good. But when I try to login, I get this error message: Fatal error: Class '\App\User' not found in C:\..\vendor\illuminate\auth\EloquentUserProvider.php on line 126

I do not want the validation of users to be done on a database since I will just have one credential so most likely it will just get the username and password on a variable and validate it from there.

Btw, I reference it thru this laracast tutorial. Though it is a Laravel app tutorial, I am implementing it on Lumen app.

  • 写回答

3条回答 默认 最新

  • dongyong6428 2015-12-25 06:36
    关注

    I am answering my own question as I was able to make it work but would still like to know more insights from others regarding my solution and the proper laravel way of doing it.

    I was able to work on this by creating a custom middleware that does this:

    <?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);
        }
    
    }
    

    If you'll look into the code, it is pretty basic and works well. Though I am wondering if there is a "Laravel" way of doing this as the code above is a plain PHP code that does HTTP basic authentication.

    If you'll notice, validation of username and password is hard coded on the .env file as I do not see the need for database access for validation.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历