下面由laravel教程栏目给大家介绍laravel auth原理浅析,希望对需要的朋友有所帮助!
由于公司最近使用laravel-admin做后台,接触了下laravel框架,不得不说,laravel社区的力量以及生态确实挺强大。
但是公司内部业务都处于java端,后台全部都是调javaapi,因此使用laravel的特性就得大打折扣了,首先eloquent模型完全不能用,我这边把业务分开来,只存了3张表,这是laravel-admin自带的表。
laravel-admin带了9张表,由于用户登录业务全保存在api端,自带的表功能被我割舍了。因此需要自己实现api登录的逻辑,而又必须走laravel auth认证。
原理解读
// 使用下面这个命令laravel会自动为我们生成auth路由和认证模块。跟着代码往下解读。 php artisan make:auth // http/controllers/auth/logincontroller 使用了 authenticatesusers
其中 下面这三个方法诠释了登录逻辑的全部。
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); } protected function attemptlogin(request $request) { return $this->guard()->attempt( $this->credentials($request), $request->has('remember') ); } protected function guard() { return auth::guard(); }
控制器会去寻找auth::guard(), 那这个auth::guard()是个什么东西呢,
首先 auth 是系统的单例,原型在
illuminate\auth\authmanager;
顾名思义,是一个auth管理模块,实现了认证工厂模式接口guards(),
public function __construct($app) { $this->app = $app; $this->userresolver = function ($guard = null) { return $this->guard($guard)->user(); }; } // auth::guard();就是调用了这个方法。 public function guard($name = null) { // 首先查找$name, 没有就使用默认的驱动, $name = $name ?: $this->getdefaultdriver(); // 意思就是要实例化出这个驱动并且返回, return isset($this->guards[$name]) ? $this->guards[$name] : $this->guards[$name] = $this->resolve($name); } // 默认的驱动是从配置文件里面读取的,/config/auth.php default配置项 public function getdefaultdriver() { return $this->app['config']['auth.defaults.guard']; } // 这里是构造auth-guard驱动 protected function resolve($name) { $config = $this->getconfig($name); if (is_null($config)) { throw new invalidargumentexception("xxx"); } // 这里是如果你自己实现的驱动就返回 if (isset($this->customcreators[$config['driver']])) { return $this->callcustomcreator($name, $config); } // 这里是系统默认两个类分别是 // session 和 token 这里主要讲 sessionguard . $drivermethod = 'create'.ucfirst($config['driver']).'driver'; if (method_exists($this, $drivermethod)) { return $this->{$drivermethod}($name, $config); } throw new invalidargumentexception("xxx"); }
接下来看看配置文件 auth.php
// auth::guard() ,不传参数,就调用默认的default.guard , 'defaults' => [ 'guard' => 'web', 'passwords' => 'users', ], // 系统的guard .默认支持 "database", "eloquent",意思就是说你的provider必须是这两个实例中的一个, 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], ], // 这个就是上面的provider了,你使用哪一个provider作为你的auth::guard()返回的 // 模型 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => app\user::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ],
也就是说终归到底,auth::guard(), 在默认配置里面是给我反回了一个sessionguard .
主要看下面4个方法
namespace illuminate\auth;class sessionguard{ public function attempt(array $credentials = [], $remember = false) { // 这里触发 试图登录事件,此时还没有登录 $this->fireattemptevent($credentials, $remember); $this->lastattempted = $user = $this->provider->retrievebycredentials($credentials); // 这里会调用hasvalidcredentials,其实就是验证用户名和密码的一个过程 if ($this->hasvalidcredentials($user, $credentials)) { // 如果验证通过了,就调用login方法 . $this->login($user, $remember); return true; } // 否则就触发登录失败事件,返回假 $this->firefailedevent($user, $credentials); return false; } // 这里是登录用户的操作,就是说调用这个方法已经是合法用户了,必须是一个// authenticatablecontract 的实例 . public function login(authenticatablecontract $user, $remember = false) { // 直接更新session,这里就是把session存起来,session的键在该方法的 // getname() 里边, $this->updatesession($user->getauthidentifier()); if ($remember) { $this->ensureremembertokenisset($user); $this->queuerecallercookie($user); } // 触发登录事件,已经登录了这个时候, $this->fireloginevent($user, $remember); // 将user对象保存到sessionguard , 后续的类访问auth::user();直接拿到 $this->setuser($user); } // 这里就是经常使用到的 auth::user()了,具体如何返回看authmanager里面的 // __call public function user() { if ($this->loggedout) { return; } if (! is_null($this->user)) { return $this->user; } // 这里读取session拿到user的id , $id = $this->session->get($this->getname()); $user = null; // 如果拿到了id ,查找到该user if (! is_null($id)) { if ($user = $this->provider->retrievebyid($id)) { $this->fireauthenticatedevent($user); } } $recaller = $this->recaller(); if (is_null($user) && ! is_null($recaller)) { $user = $this->userfromrecaller($recaller); if ($user) { $this->updatesession($user->getauthidentifier()); $this->fireloginevent($user, true); } } return $this->user = $user; } // 这里就直接返回用户id了, public function id() { if ($this->loggedout) { return; } return $this->user() ? $this->user()->getauthidentifier() : $this->session->get($this->getname()); }}
大体上用户登录的流程就完了,简单过程就是
//伪代码$credentials = $request()->only(['username' ,'password']);if(auth::guard("session")->attempt($credentials)){ // 登录成功}else{ // 登录失败}
实现用户登录之后才能访问的控制器/方法
route::get("/home")->middleware("auth");// auth middleware 是在app/http/kernel中注册的,// 类名是 \illuminate\auth\middleware\authenticate::class// 解析过程实质上是这个方法: public function handle($request, closure $next, ...$guards) { $this->authenticate($guards); return $next($request); } protected function authenticate(array $guards) { // 默认情况下会去 auth中寻找authenticate这个方法 if (empty($guards)) { return $this->auth->authenticate(); } // 如果middleware中传了参数,会遍历一遍,不通过就抛出异常 foreach ($guards as $guard) { if ($this->auth->guard($guard)->check()) { return $this->auth->shoulduse($guard); } } throw new authenticationexception('unauthenticated.', $guards); } //sessionguard 中的authenticate其实也就是调用了一遍user方法。 public function authenticate() { if (! is_null($user = $this->user())) { return $user; } throw new authenticationexception; }
第一次写文,有错误请指出谢谢!
以上就是关于laravel auth原理浅析的详细内容。
