Applying Middleware

Making routes go through middleware before being sent to controllers.

When we define a route, we can apply a middleware to it, the request, then takes the path Router -> Middleware -> Controller rather than directly going to Controller from the Router. This can be used to put some routes behind authentication. To add authentication to routes, we can use Auth class provided in sirJuni\Framework\Middleware\Auth . It is very simple to do using this framework, in code we just have to write

Router::add_route('GET', '/admin', [AdminController::class, 'index'])->middleware(Auth::class);

If the user is authenticated using the Auth::login() method, about which you will learn in the Auth module, the user can visit /admin otherwise they will be redirected to the login page. Now, we need to tell Auth class where the login page is and we do that by Auth::set_fallback_route('/path/to/login');

use sirJuni\Framework\Middleware\Auth;   // add this line below the autoload.php

Auth::set_fallback_route('/login');     // if user visits /admin without authentication
// they will be redirected to /login

Last updated