Lumen 中实现用户认证的配置文件位于config/auth.php。
在底层代码中,Lumen 的认证组件由“guards”和“providers”组成,Guard 定义了用户在每个请求中如何实现认证,例如,Laravel 通过 session guard来维护 Session 存储的状态、Cookie 以及 token guard,token guard 是认证用户发送请求时带的“API token”。
Provider 定义了如何从持久化存储中获取用户信息,Lumen 底层支持通过 Eloquent 和数据库查询构建器两种方式来获取用户,如果需要的话,你还可以定义额外的 Provider。
通过 Auth 门面访问认证用户:
$user = Auth::user();判断某个用户是否登录到应用,可以使用 Auth 门面的 check方法,如果用户通过认证则返回 true:
if (Auth::check()) { // The user is logged in... } 可以通过 Illuminate\Http\Request 实例访问认证用户:if ($request->user()) { // $request->user() 返回认证用户实例... }
lumen 认证的流程:
bootstrap/app.php: $app->routeMiddleware([ 'auth' => App\Http\Middleware\Authenticate::class, ]);如果用到中间件,生成auth factory的实例
App\Http\Middleware\Authenticate: public function __construct(Illuminate\Contracts\Auth\Factory $auth) { $this->auth = $auth; } public function handle($request, Closure $next, $guard = null) { if ($this->auth->guard($guard)->guest()) { return response('Unauthorized.', 401); } return $next($request); } authServiceProvider: $app->register(App\Providers\AuthServiceProvider::class); App\Providers\AuthServiceProvider: public function boot() { $this->app['auth']->viaRequest('api', function ($request) { if ($request->input('api_token')) { return User::where('api_token', $request->input('api_token'))->first(); } }); } 注:$this->app['auth'] 为Illuminate\Auth\AuthManager实例: $app->$availableBindings = [ 'auth' => 'registerAuthBindings', 'auth.driver' => 'registerAuthBindings', 'Illuminate\Auth\AuthManager' => 'registerAuthBindings', ......]; Laravel\Lumen\Application: protected function registerAuthBindings() { $this->singleton('auth', function () { return $this->loadComponent('auth', 'Illuminate\Auth\AuthServiceProvider', 'auth'); }); $this->singleton('auth.driver', function () { return $this->loadComponent('auth', 'Illuminate\Auth\AuthServiceProvider', 'auth.driver'); }); $this->singleton('Illuminate\Contracts\Auth\Access\Gate', function () { return $this->loadComponent('auth', 'Illuminate\Auth\AuthServiceProvider', 'Illuminate\Contracts\Auth\Access\Gate'); }); } protected function registerAuthenticator() { $this->app->singleton('auth', function ($app) { $app['auth.loaded'] = true; return new AuthManager($app); }); $this->app->singleton('auth.driver', function ($app) { return $app['auth']->guard(); }); } Illuminate\Auth\AuthManager: public function guard($name = null) { $name = $name ?: $this->getDefaultDriver(); //$this->app['config']['auth.defaults.guard'] 即“api” return isset($this->guards[$name]) ? $this->guards[$name] : $this->guards[$name] = $this->resolve($name); // createSessionDriver 或 createTokenDriver } }
修改config/auth.php:
'defaults' => [ 'guard' => env('AUTH_GUARD', 'api'), ], 'guards' => [ 'api' => ['driver' => 'token', 'provider'=>'api'], ], 'providers' => [ 'api' => [ 'driver' => 'eloquent', 'model' => 'AppUser' ], ],