Lumen HTTP Basic Authentication without use of database

basagabi picture basagabi · Dec 24, 2015 · Viewed 12.7k times · Source

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.

Answer

basagabi picture basagabi · Dec 25, 2015

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.