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条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用