用户认证

更新时间: 2019-08-01 16:47

简介

Lumen 虽然与 Laravel 使用了相同的底层类库实现,但是因 Lumen 面向的是无状态 API 的开发,不支持 session,所以默认的配置不同。Lumen 必须使用无状态的机制来实现认证,如 API 令牌(Token)。

开始

认证服务提供者

注意: 在使用 Lumen 的认证功能前,请取消 bootstrap/app.php 文件中的 AuthServiceProvider 调用代码的注释。

AuthServiceProvider 存放在 app/Providers 文件夹中,此文件中只有一个 Auth::viaRequest 调用。viaRequest 会在系统需要认证的时候被调用,此方法接受一个 Closure (匿名函数)参数。在此 Closure (匿名函数)内,你可以任意的解析 App\User 并返回,或者在解析失败时返回 null

$this->app['auth']->viaRequest('api', function ($request) {
    // 返回 User 或 null...
});

同样,你可以使用你期望的方式取得用户认证,比如在请求头或查询字符串中使用 API 令牌、请求中的 bearer 令牌,或者使用应用程序需要的任何其他方法。

如果你的项目没有使用 Eloquent ,你需要返回一个 Illuminate\Auth\GenericUser 类的实例。这个类接受一个属性数组作为构造函数的唯一参数:

use Illuminate\Auth\GenericUser;

return new GenericUser(['id' => 1, 'name' => 'Taylor']);

获取已认证的用户信息

就像 Laravel 框架一样,你可以使用 Auth::user() 方法获取当前用户,或者,你可以在 Illuminate\Http\Request 实例上使用 $request->user() 方法:

use Illuminate\Http\Request;

$router->get('/post/{id}', ['middleware' => 'auth', function (Request $request, $id) {
    $user = Auth::user();

    $user = $request->user();

    //
}]);

注意: 如果你想使用 Auth::user() 来获取当前的认证用户,你需要去掉 bootstrap/app.php 文件中 $app->withFacades() 方法调用的注释。

当然,所有你想要认证的路由,都可以分配给 auth 中间件 ,但需要你去掉 bootstrap/app.php 文件中对 $app->routeMiddleware() 调用的注释:

$app->routeMiddleware([
    'auth' => App\Http\Middleware\Authenticate::class,
]);

查看更多 Laravel 中文文档 信息

Programming Amazon Web Services

Programming Amazon Web Services

James Murty / O'Reilly Media / 2008-3-25 / USD 49.99

Building on the success of its storefront and fulfillment services, Amazon now allows businesses to "rent" computing power, data storage and bandwidth on its vast network platform. This book demonstra......一起来看看 《Programming Amazon Web Services》 这本书的介绍吧!

MD5 加密

MD5 加密

MD5 加密工具

HEX HSV 转换工具

HEX HSV 转换工具

HEX HSV 互换工具