Laravel5.5 source code Detailed--AUTH middleware

Source: Internet
Author: User
Tags auth closure extend
Laravel5.5 Source code detailed –auth middleware

In order to reflect the full picture, the previous Code section did not do too much pruning, focusing on the annotated part of the special addition. The original comments are deleted to reduce the length of the reading. This article focuses on the following process explanations, which are more detailed.

If you look at official documents, you often don't know what to do when you run into problems. Therefore, skilled use, should be based on a deep understanding of the source code. And its process is the first step to understand the source code. Understand these, the development of the ability to easily.

Registered in the App\http\kernel

<?php namespace App\http;
Use Illuminate\foundation\http\kernel as Httpkernel; Class Kernel extends Httpkernel {//Global Http middleware protected $middleware = [\ILLUMINATE\FOUNDATION\HTTP\MIDDL Eware\checkformaintenancemode::class, \illuminate\foundation\http\middleware\validatepostsize::class, \App
        \http\middleware\trimstrings::class, \illuminate\foundation\http\middleware\convertemptystringstonull::class,

    \app\http\middleware\trustproxies::class,]; 
            Routing middleware protected $middlewareGroups = [' Web ' => [\app\http\middleware\encryptcookies::class, \illuminate\cookie\middleware\addqueuedcookiestoresponse::class, \illuminate\session\middleware\s Tartsession::class,//\illuminate\session\middleware\authenticatesession::class, \Illuminate\View \middleware\shareerrorsfromsession::class, \app\http\middleware\verifycsrftoken::class, \Illuminat E\routIng\middleware\substitutebindings::class,], ' API ' => [' throttle:60,1 ', ' Bind

   Ings ',],]; Middleware protected that may need to be grouped or used separately $routeMiddleware = [' Auth ' => \illuminate\auth\middleware\authenticate::class , ' Auth.basic ' => \illuminate\auth\middleware\authenticatewithbasicauth::class, ' bindings ' => \Illum
        Inate\routing\middleware\substitutebindings::class, ' Can ' => \illuminate\auth\middleware\authorize::class, ' Guest ' => \app\http\middleware\redirectifauthenticated::class, ' throttle ' => \illuminate\routing\middle
Ware\throttlerequests::class,];
 }

As you can see, auth middleware is part of the middleware that may need to be grouped or used separately, but you may also adjust it as needed.

' Auth ' => \illuminate\auth\middleware\authenticate::class

For the operating mechanism of middleware, please refer to the other text,

Laravel5.5 source code Detailed-middleware middleware analysis

Open \illuminate\auth\middleware\authenticate,

<?php namespace Illuminate\auth\middleware;
Use Closure;
Use illuminate\auth\authenticationexception;

Use Illuminate\contracts\auth\factory as Auth;
    Class Authenticate {protected $auth;
    Public function __construct (Auth $auth) {//inject Illuminate\auth\authmanager factory class $this->auth = $auth;

        The public function handle ($request, Closure $next, ... $guards) {$this->authenticate ($guards);
    Return $next ($request);

            protected function authenticate (array $guards) {//If guard is not specified, use default setting if (Empty ($guards)) { Use Illuminate\auth\authmanager\__call () to get the Sessionguard instance,//and call it (actually guardhelpers) authenticat

        E () method for authentication return $this->auth->authenticate (); ///If there is a specified guard, use one of the first successfully authenticated foreach ($guards as $guard) {if $this->auth->guard ($gu
             ard)->check ()) {//Get this request guard, (subsequent requests will also pass this guard)   return $this->auth->shoulduse ($guard);
    } throw new Authenticationexception (' unauthenticated. ', $guards); }
}

Note that the $this->auth is passed into the Illuminate\contracts\auth\factory interface at construction time, the implementation class is Illuminate\auth\authmanager, and then the Let's take a look at this class, paying special attention to the annotations in the Resolve function,

<?php namespace Illuminate\auth;
Use Closure;
Use InvalidArgumentException;

Use Illuminate\contracts\auth\factory as factorycontract;
    Class AuthManager implements Factorycontract {use createsuserproviders;
    protected $app;
    protected $customCreators = [];
    protected $guards = [];

    protected $userResolver;
        Public function __construct ($app) {$this->app = $app;
        $this->userresolver = function ($guard = null) {return $this->guard ($guard)->user ();
    }; The Public function guard ($name = null) {//Getdefaultdriver () returns the web $name = $name?: $this   
        ->getdefaultdriver (); return $this->guards[$name]??
    $this->guards[$name] = $this->resolve ($name);
        } protected function Resolve ($name) {//Array:2 ["Driver" => "session", "Provider" => "users"] array:2 ["Driver" => "token", "Provider" => "users"] $config = $this->getConfig ($name);
        if (Is_null ($config)) {throw new InvalidArgumentException ("Auth guard [{$name}] is not defined.");  } if (Isset ($this->customcreators[$config [' Driver ']]) {return $this->callcustomcreator ($name,
        $config); }//"Web" => "createsessiondriver"//"API" => "createtokendriver" $driverMethod = ' Create '. Ucfirst ($config [' Driver ']). '

        Driver ';  if (Method_exists ($this, $driverMethod)) {//Sessionguard ("Web", ["Driver" => "session", "Provider" => "Users"]//Tokenguard ("API", ["Driver" => "token", "Provider" => "users"]) return $this-&G T {$driverMethod}
        ($name, $config);
    } throw new InvalidArgumentException ("Auth guard driver [{$name}] is not defined."); protected function Callcustomcreator ($name, array $config) {return $this->customcreators[$config [' d River ']] ($this->app, $name, $config); The Public Function createsessiondriver ($name, $config) {$provider = $this->createuserprovider ($config [ ' Provider ']??

        NULL);

        Create Sessionguard here, $guard = new Sessionguard ($name, $provider, $this->app[' Session.store '));
        if (method_exists ($guard, ' Setcookiejar ')) {$guard->setcookiejar ($this->app[' Cookie '));
        The Setdispatcher () function of the Sessionguard is called here, associated with the dispatcher, which is described later.
        if (method_exists ($guard, ' Setdispatcher ')) {$guard->setdispatcher ($this->app[' events ')); } if (Method_exists ($guard, ' setrequest ')) {$guard->setrequest ($this->app->refresh (' request
        ', $guard, ' setrequest ');
    return $guard; The Public Function createtokendriver ($name, $config) {$guard = new Tokenguard ($this->crea

        Teuserprovider ($config [' Provider ']?? null), $this->app[' request ']); $thIs->app->refresh (' request ', $guard, ' setrequest ');
    return $guard; } protected function GetConfig ($name) {return $this ' config ' [] auth.guards.{
    $name} "];
    The Public Function Getdefaultdriver () {return $this->app[' config '] [' auth.defaults.guard '];

        The Public Function Shoulduse ($name) {$name = $name?: $this->getdefaultdriver ();

        $this->setdefaultdriver ($name);
        $this->userresolver = function ($name = null) {return $this->guard ($name)->user ();
    };
    The Public Function Setdefaultdriver ($name) {$this->app[' config '] [' auth.defaults.guard '] = $name; The Public Function viarequest ($driver, callable $callback) {return $this->extend ($driver, function () Use ($callback) {$guard = new Requestguard ($callback, $this->app[' request '), $this->createuserprovider (

            )); $this->app->refresh (' reQuest ', $guard, ' setrequest ');
        return $guard;
    });
    The Public Function Userresolver () {return $this->userresolver;
        The Public Function resolveusersusing (Closure $userResolver) {$this->userresolver = $userResolver;
    return $this;

        The public function extend ($driver, Closure $callback) {$this->customcreators[$driver] = $callback;
    return $this; The Public function provider ($name, Closure $callback) {$this->customprovidercreators[$name] = $callbac
        K
    return $this;
    The Public Function __call ($method, $parameters) {return $this->guard ()->{$method} (... $parameters);
 }
}

In this case, the equivalent of __call ("Authenticate", []), where $this->guard () is Sessionguard, which is obtained by AuthManager's function resolve (' web '),

Simply put, in AuthManager, the function guard () calls the function resolve (' web '), which invokes the Createsessiondriver instantiation of Sessionguard.

Sessionguard {#329
  #name: web
  #lastAttempted: null
  #viaRemember: false
  #session: Store {#314 ▶}
  #cookie: Cookiejar {#302 ▶}
  #request: request {#42 ▶}
  #events: Dispatcher {#26 ▶}
  #loggedOut: false
  #recallAttempted: false
  #user: null
  #provider: eloquentuserprovider {#326 ▶}
}

A bit deeper in this process, is that in Illuminate\auth\authmanager, Createsessiondriver () invokes the Sessionguard Setdispatcher () function and makes an injection (association) ,

    The Setdispatcher () function of Sessionguard is called here
    if (method_exists ($guard, ' Setdispatcher ')) {
        $guard-> Setdispatcher ($this->app[' events ']);
    }

In the setdispatcher of Sessionguard,

    Public Function Setdispatcher (Dispatcher $events)
    {
        $this->events = $events;
    }

Here \ $events Prototype is illuminate\contracts\events\dispatcher this interface, and its instance is

\illuminate\events\dispatcher, this association can be seen very clearly in illuminate\foundation\application,

' Events ' => [\illuminate\events\dispatcher::class, \illuminate\contracts\events\dispatcher::class],

AuthManager did not authenticate (), so \illuminate\auth\middleware\authenticate inside of this sentence

$this->guard ()->authenticate () is not actually able to find AuthManager authenticate () at the time of execution, it will pass the AuthManager

Public Function __call ($method, $parameters)
{return
    $this->guard ()->{$method} (... $parameters);

To invoke the Authenticate () function in Sessionguard, Sessionguard also has no authenticate, it is through the macro use Guardhelpers, macroable; Called the Authenticate () in Illuminate\auth\guardhelpers,

<?php
namespace Illuminate\auth;
Use Illuminate\contracts\auth\userprovider;
Use illuminate\contracts\auth\authenticatable as authenticatablecontract;

Trait guardhelpers
{
    protected $user;
    protected $provider;

    Public function Authenticate ()
    {
        if (! is_null ($user = $this->user ())) {return
            $user;
        }

        throw new Authenticationexception;
    }

From $this->user () here to where the real authentication is, other Auth validation functions are the same principle, such as when you use Auth::check () to determine whether a user is logged in, the actual calling function is also illuminate\auth\ Check () in the Guardhelpers,

    Public function Check ()
    {return
        ! Is_null ($this->user ());
    

Similarly, this guardhelpers also has Auth::id (), auth::guest () and so on,

So, the most critical thing is to look at the user () function in Illuminate\auth\sessionguard, like the following,

 Public function User () {if ($this->loggedout) {return; } if (! Is_null ($this->user)) {return; 

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.