Middleware


Introduction

Middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Shadow includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application. Of course, additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application. There are several middleware included in the Shadow framework, including middleware for authentication and CSRF protection. All of these middleware are located in the application/Http/Middlewares directory.


Defining Middleware

To create a new middleware, use the create:middleware Kapitan command:

<?php

namespace App\Middlewares;

use Shadow\Authentication\Auth;

class AuthMiddleware
{
    public function __construct() {

    }

    public function init() {        
        if(Auth::checkSession()) {
            return true;
        }
        
        return redirect('backend/login');
    }
}

Registering Middleware

You have to first register middleware in application/Http/Routes/web.html file before using it

$router->middleware('auth', 'AuthMiddleware@init');

Assigning Middleware To Routes

Once the middleware has been defined in application/Http/Routes/web.html file, you may use the middleware method to assign middleware to a route:

$router->get('/', ['before' => 'auth'], function() {
    return view('welcome');
});