Laravel permission Control Organization-middleware and laravel Middleware

Source: Internet
Author: User

Laravel permission Control Organization-middleware and laravel Middleware
Introduction

HTTP middleware provides a convenient mechanism to filter HTTP requests entering the application. For example, Laravel contains a middleware by default to verify user authentication. if the user has not been authenticated, middleware directs the user to the logon page. However, if the user passes authentication, middleware will allow the request to proceed further.

Of course, in addition to identity authentication, middleware can also be used to execute a variety of tasks. CORS middleware is responsible for adding appropriate response headers for all the responses to be exited, A Log Middleware can record all requests passed into the application. The Laravel framework has some built-in middleware, including maintenance, authentication, and CSRF protection. All Middleware is located in the app/Http/Middleware directory.

Understanding: if your application-routing, Controller, and business logic-is the green part in the figure, you can clearly see that user requests can reach your application through multiple middle layers first, then, more intermediate layers are used for processing. Each specific middle layer can be processed before and after the application logic, or both before and after the application logic.

This is how middleware implements the modifier mode: it captures the request, performs some processing, and then returns the processed request object to the next stack layer.

Laravel uses middleware by default to process encryption/decryption and cookie queues, read and write sessions, however, you can also use middleware to add any operation layer you need to the request/response ring. For example, speed limit and custom request parsing.

Create

To create a new middleware, run the "make: middleware" Artisan command:

php artisan make:middleware OldMiddleware

This command will create a class named OldMiddleware in the app/Http/Middleware directory. In this middleware, we only allow users older than 200 to access the route. Otherwise, we will redirect the user to the URI of "home.

<?php namespace App\Http\Middleware;class OldMiddleware {    /**     * Run the request filter.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @return mixed     */    public function handle($request, Closure $next)    {        if ($request->input('age') < 200)        {            return redirect('home');        }        return $next($request);    }}

As you can see, the base of all middleware is the handle method, which accepts two parameters:

$ Request: Illuminate Request object

$ Next: Closure (anonymous function), which passes the request object to the subsequent middleware

In fact, the function of filter is implemented.

Before/After Middleware

Specifying a middleware before and after a request depends on the middleware itself. This middleware can execute some pre-operations before the request:

<?php namespace App\Http\Middleware;class BeforeMiddleware implements Middleware {    public function handle($request, Closure $next)    {        // Perform action        return $next($request);    }}

Then, this middleware can also perform some post operations after the request:

<?php namespace App\Http\Middleware;class AfterMiddleware implements Middleware {    public function handle($request, Closure $next)    {        $response = $next($request);        // Perform action        return $response;    }}
Register/use middleware 1. Global Middleware

If you want the middleware to be executed by all HTTP requests, you only need to add the middleware class to the $ middleware attribute list of app/Http/Kernel. php.

/*** The application's global HTTP middleware stack. ** @ var array */protected $ middleware = ['illuminate \ Foundation \ Http \ Middleware \ checkformaintenancemode', 'illuminate \ Cookie \ Middleware \ EncryptCookies ', 'illuminate \ Cookie \ Middleware \ done', 'illuminate \ Session \ Middleware \ StartSession ', 'illuminate \ View \ Middleware \ assumerrorsfromsession', 'app \ Http \ Middleware \ done ', 'app \ Http \ Middleware \ OldMiddleware ', // register and use];
2. Assign middleware to the route

If you want to assign middleware to a specific route, you must first put the middleware in app/Http/Kernel. php configures a key value. By default, the $ routeMiddleware attribute in this file contains the middleware currently configured by Laravel, you only need to add a set of custom key values to the list. Once the middleware is defined in the HTTP kernel File, you can use the middleware key value in the routing options to assign it.

protected $routeMiddleware = [    'auth' => 'App\Http\Middleware\Authenticate',    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',    'guest' => 'App\Http\Middleware\RedirectIfAuthenticated'  ];
2. Middleware for Routing
Route::get('admin/profile', ['middleware' => 'auth', function(){    //}]);
3. Middleware used in Controllers
...use Illuminate\Routing\Controller;class AwesomeController extends Controller {  public function __construct()  {    $this->middleware('csrf');    $this->middleware('auth', ['only' => 'update'])  }}
Consumable Middleware

In some cases, the middleware needs to be executed only after the HTTP response has been sent to the client. For example, the "session" middleware built in Laravel saves the session data only after the response has been sent to the client. To achieve this, you need to define the middleware as "terminable 」.

use Closure;use Illuminate\Contracts\Routing\TerminableMiddleware;class StartSession implements TerminableMiddleware {    public function handle($request, Closure $next)    {        return $next($request);    }    public function terminate($request, $response)    {        // Store the session data...    }}

As you can see, in addition to defining the handle method, TerminableMiddleware defines a terminate method. This method receives requests and responses. Once terminable middleware is defined, you need to add it to the global middleware list of the HTTP kernel File.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.