Search code examples
laravelauthenticationmiddleware

Laravel 5.7 auth behavior


I'm new to Laravel and have been tracing it's code several days now to understand its behavior but to no avail.

Suppose I add middleware to a route like this

Route::group(["middleware" => ["web", "auth:web", "auth:custom"]], function() {
    Route::view("/about", "about");
});
  1. Does the /about route go through auth:web followed by auth:custom? If not, what is the behavior?

  2. How do I create a auth:custom guard that does not conflict with auth:web? The current behavior is that, if auth:web is authenticated, auth:custom follows it's status, I suspect they are sharing the same session variable.

I'm really new to Laravel and this appears to be a mix of route, auth and middleware. Hope someone can point me in the right direction. Thank you.


Solution

  • 1 - Your route will use middlewares from App\Providers\RouteServiceProvider. See:

    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }
    

    Every middleware you write will be executed in the order you define. If one middleware fails, $next($request); won't be called. So the next middleware won't get activated.

    2- These auth:web and auth:custom middlewares are the 'auth middleware' calls, but with different parameters. Everything after : are being sent to handle method of the middleware as parameters.

    The auth middleware is defined under App\Http\Kernel class under $routeMiddleware var:

    'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
    

    and here is the handle method:

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle($request, Closure $next, ...$guards)
    {
        $this->authenticate($guards);
    
        return $next($request);
    }
    

    Your 'web' or 'custom' parameter goes to ...$guards parameter.

    By the way, there is no predefined 'custom' guard. You have to write your own custom guard and define it under config/auth.php, guards array:

    'guards' => [
        'web' => [ // This is the web guard (auth:web)
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [ // and this the api guard (auth:api)
            'driver' => 'token',
            'provider' => 'users',
        ],
    ],
    

    Then you can expect laravel auth middleware to authenticate using your custom guard like auth:custom or auth:acme.