Laravel中的Auth

Laravel中的Auth

laravel中有一個組件叫auth,auth組件提供了整個框架的認證功能,這裏想簡單追蹤一下它的實現邏輯。
php

首先從 php artisan make:auth 開始

# Illuminate\Auth\Console\AuthMakeCommand.php

public function handle()
{
    // 建立存放auth前端界面的目錄和文件
    // 模版存放在Auth\Console的stubs下
    $this->createDirectories();
    $this->exportViews();

    if (! $this->option('views')) {
        // 生成HomeController控制器文件
        file_put_contents(
            app_path('Http/Controllers/HomeController.php'),
            $this->compileControllerStub()
        );
        // 生成auth相關路由
    file_put_contents(
        base_path('routes/web.php'),
        file_get_contents(__DIR__.'/stubs/make/routes.stub'),
        FILE_APPEND
        );
    }
}

生成文件resources/views/auth、 resources/layouts路由文件 web.php 、和 Http/Controllers/Auth 下的控制器前端

說一說csrf-token

<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
function csrf_token()
    {
        $session = app('session');

        if (isset($session)) {
            return $session->token();
        }

        throw new RuntimeException('Application session store not set.');
    }

LoginController的login方法

public function login(Request $request)
    {
                // 檢查請求體
        $this->validateLogin($request);
                // 判斷是否請求失敗太屢次
        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);

            return $this->sendLockoutResponse($request);
        }
                // 判斷是否驗證經過
        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }
                // 記錄請求失敗次數
        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

登陸驗證方法attemptLogin

經過 Auth::guard() 引導到 Illuminate\Auth\AuthManager
先看  服務提供者  AuthServiceProvider
AuthServiceProvider註冊四個服務laravel

protected function registerAuthenticator()
    {
        $this->app->singleton('auth', function ($app) {
            $app['auth.loaded'] = true;
                        // 生成一個AuthManager實例
            return new AuthManager($app);
        });

        $this->app->singleton('auth.driver', function ($app) {
            return $app['auth']->guard();
        });
    }
protected function registerUserResolver()
    {
        $this->app->bind(
            AuthenticatableContract::class, function ($app) {
                return call_user_func($app['auth']->userResolver());
            }
        );
    }
protected function registerAccessGate()
    {
        $this->app->singleton(GateContract::class, function ($app) {
            return new Gate($app, function () use ($app) {
                return call_user_func($app['auth']->userResolver());
            });
        });
    }
protected function registerRequestRebindHandler()
    {
        $this->app->rebinding('request', function ($app, $request) {
            $request->setUserResolver(function ($guard = null) use ($app) {
                return call_user_func($app['auth']->userResolver(), $guard);
            });
        });
    }

生成一個AuthManager實例
AuthManager中的trait CreatesUserProviders
這個trait是用來綁定一個用戶認證的Eloqument服務提供者web

public function __construct($app)
    {
                // 綁定application實例
        $this->app = $app;
                // 綁定一個閉包,用於解析用戶。
                // 經過$guard來肯定用戶解析用戶的方法
        $this->userResolver = function ($guard = null) {
            return $this->guard($guard)->user();
        };
    }

protected function resolve($name)
    {
        $config = $this->getConfig($name);

                // 根據配置調用不一樣的解析用戶的驅動方法
        $driverMethod = 'create'.ucfirst($config['driver']).'Driver';

        if (method_exists($this, $driverMethod)) {
            return $this->{$driverMethod}($name, $config);
        }
    }

分別定位的兩個方法api

public function createSessionDriver($name, $config)
    {
                //     根據配置文件建立一個相應的provider
        $provider = $this->createUserProvider($config['provider'] ?? null);
                
                $guard = new SessionGuard($name, $provider, $this->app['session.store']);

        return $guard;
    }
    
    public function createTokenDriver($name, $config)
    {
        $guard = new TokenGuard(
            $this->createUserProvider($config['provider'] ?? null),
            $this->app['request'],
            $config['input_key'] ?? 'api_token',
            $config['storage_key'] ?? 'api_token'
        );
        return $guard;
    }

因而獲得 $this->guard($guard) 的user()方法
先看如何實例一個TokenGuard類session

public function __construct(UserProvider $provider, Request $request, $inputKey = 'api_token', $storageKey = 'api_token')
    {
        $this->request = $request;
        $this->provider = $provider;
        $this->inputKey = $inputKey;
        $this->storageKey = $storageKey;
    }
# Illuminate\Auth\TokenGuard

    public function user()
    {
        if (! is_null($this->user)) {
            return $this->user;
        }

        $user = null;
                // 從request中獲取token
        $token = $this->getTokenForRequest();

        if (! empty($token)) {
                        // 經過用戶provider中的retrieveByCredentials方法來判斷用戶是否定證成功
            $user = $this->provider->retrieveByCredentials(
                [$this->storageKey => $token]
            );
        }

        return $this->user = $user;
    }

上面都是通用的加載引導調用功能,下面的用戶服務提供者則是能夠修改自定義的認證的具體功能閉包

認證綁定的用戶數據提供者

# Illuminate\Auth\DatabaseUserProvider

    public function retrieveByCredentials(array $credentials)
    {
        if (empty($credentials) ||
           (count($credentials) === 1 &&
            array_key_exists('password', $credentials))) {
            return;
        }
        $query = $this->conn->table($this->table);

        foreach ($credentials as $key => $value) {
            if (Str::contains($key, 'password')) {
                continue;
            }

            if (is_array($value) || $value instanceof Arrayable) {
                $query->whereIn($key, $value);
            } else {
                $query->where($key, $value);
            }
        }
        
        $user = $query->first();
        
        // 返回auth用戶數據包
        return $this->getGenericUser($user);
    }
相關文章
相關標籤/搜索