Authentication in Lumen

Modify app.php

Uncomment:

$app->routeMiddleware( [
    'auth' => App\Http\Middleware\Authenticate::class,
] );

Uncomment:

// $app->register(App\Providers\AppServiceProvider::class);
$app->register( App\Providers\AuthServiceProvider::class );
// $app->register(App\Providers\EventServiceProvider::class);

Control the response

The response in case of an non-authorized situation can be found in the Authenticate.php in the `Http\Middleware' folder.

public function handle($request, Closure $next, $guard = null)
{
    if ($this->auth->guard($guard)->guest()) {
       return response('Unauthorized.', 401);
    }
   return $next($request);
}

How the authentication is checked

This can be found in the AuthServiceProvider.php in the Providers folder.

public function boot()
{
    // Here you may define how you wish users to be authenticated for your Lumen
    // application. The callback which receives the incoming request instance
    // should return either a User instance or null. You're free to obtain
    // the User instance via an API token or any other method necessary.

    $this->app['auth']->viaRequest('api', function ($request) {
        if ($request->input('api_token')) {
            return User::where('api_token', $request->input('api_token'))->first();
        }
    });
}

Routes and Middleware

This is just a sample that could be placed in the web.php file in the `routes' folder:

$app->group(['prefix' => 'api/v1'],  function ($app) {
    $app->group(['prefix' => 'posts', 'middleware' => 'auth'],  function ($app) {
        $app->post('add', 'PostController@createPost');
    });
});

which resolves for route: http://www.some.thing/api/v1/posts/add and checks for an authenticated user.

To accept api_token in the header as well

Modify the file AuthServiceProvider.php in folder Providers:

public function boot()
{
    $this->app['auth']->viaRequest('api', function ($request) {
        if ($request->header('api_token')) {
            $api_token = $request->header('api_token');
        } else {
            $api_token = $request->input('api_token');
        } 

        if ($request->input('api_token')) {
            return User::where('api_token', $api_token)->first();
        }
    });
}
Last update: October 23rd at 10:15pm