# Applying Middleware

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

```php
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');`

<pre class="language-php"><code class="lang-php">use sirJuni\Framework\Middleware\Auth;   // add this line below the autoload.php

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://shoaib-1.gitbook.io/sirjuni/middleware/applying-middleware.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
