资讯专栏INFORMATION COLUMN

学习 Lumen 用户认证 (二) —— 使用 jwt-auth 插件

姘存按 / 595人阅读

摘要:在开发中,用户认证是核心,是数据是否有保障的前提,目前主要有两种常用方式进行用户认证和。为了学习在中的使用,最好的办法就是在程序员同志网搜索有关插件,找个最多的那个拿来研究研究。

通过上一篇《学习 Lumen 用户认证 (一)》https://mp.weixin.qq.com/s/KVUQE2DUetNB2kqxHs0VDg的学习,大致懂了 Lumen 的用户认证主要使用 「api」的方式,来默认进行用户认证:

app["auth"]->viaRequest("api", function ($request) {
            if ($request->input("api_token")) {
                return User::where("api_token", $request->input("api_token"))->first();
            }
        });
    }
}

当然在实际开发中,我们不能只是简单的获取 api_token直接关联数据库查找用户信息。

在 API 开发中,用户认证是核心,是数据是否有保障的前提,目前主要有两种常用方式进行用户认证: JWT 和 OAuth2。

本文将简要说说如何利用 JWT 来进行用户认证

JWT

Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON 的开放标准 (RFC 7519)。该 token 被设计为紧凑且安全的,特别适用于分布式站点的单点登录(SSO)场景。JWT 的声明一般被用来在身份提供者和服务提供者间传递被认证的用户身份信息,以便于从资源服务器获取资源,也可以增加一些额外的其它业务逻辑所必须的声明信息,该 token 也可直接被用于认证,也可被加密。

关于 JWT 更具体的介绍,相信网上有很多帖子和文章值得参考,这里先不阐述了。

为了学习 JWT 在 Lumen 中的使用,最好的办法就是在「程序员同志网 —— GitHub」搜索有关插件,找个 stars 最多的那个拿来研究研究。

tymondesigns/jwt-auth

JSON Web Token Authentication for Laravel & Lumen

安装 jwt-auth

通过 Composer 安装:

composer require tymon/jwt-auth:"^1.0@dev"

注: 0.5.* 版本未对 Lumen 专门做封装

将 $app->withFacades() 和 auth 认证相关的注释去掉:

load();
} catch (DotenvExceptionInvalidPathException $e) {
    //
}

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We"ll use this
| application as an "IoC" container and router for this framework.
|
*/

$app = new LaravelLumenApplication(
    realpath(__DIR__."/../")
);

// 取消注释,这样就可以通过 Auth::user(),获取当前授权用户
$app->withFacades();

$app->withEloquent();

/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/

$app->singleton(
    IlluminateContractsDebugExceptionHandler::class,
    AppExceptionsHandler::class
);

$app->singleton(
    IlluminateContractsConsoleKernel::class,
    AppConsoleKernel::class
);

/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that"ll be assigned to some specific routes.
|
*/

// $app->middleware([
//    AppHttpMiddlewareExampleMiddleware::class
// ]);

// 增加 auth 中间件
$app->routeMiddleware([
    "auth" => AppHttpMiddlewareAuthenticate::class,
]);

/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application"s service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/

$app->register(AppProvidersAppServiceProvider::class);
$app->register(AppProvidersAuthServiceProvider::class);
// $app->register(AppProvidersEventServiceProvider::class);

/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/

$app->router->group([
    "namespace" => "AppHttpControllers",
], function ($router) {
    require __DIR__."/../routes/web.php";
});

return $app;

然后在 AppServiceProvider 中注册 LumenServiceProvider:

$this->app->register(TymonJWTAuthProvidersLumenServiceProvider::class);

在 Lumen 项目中,默认没有 config 文件夹,需要在项目根目录创建,并将 vendor 源代码中auth.php 复制出来,同时将 api 认证指定为「jwt」:

 [
        "guard" => env("AUTH_GUARD", "api"),
    ],

    /*
    |--------------------------------------------------------------------------
    | Authentication Guards
    |--------------------------------------------------------------------------
    |
    | Next, you may define every authentication guard for your application.
    | Of course, a great default configuration has been defined for you
    | here which uses session storage and the Eloquent user provider.
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user"s data.
    |
    | Supported: "session", "token"
    |
    */

    "guards" => [
        "api" => [
            "driver" => "jwt",
            "provider" => "users"
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | User Providers
    |--------------------------------------------------------------------------
    |
    | All authentication drivers have a user provider. This defines how the
    | users are actually retrieved out of your database or other storage
    | mechanisms used by this application to persist your user"s data.
    |
    | If you have multiple user tables or models you may configure multiple
    | sources which represent each model / table. These sources may then
    | be assigned to any extra authentication guards you have defined.
    |
    | Supported: "database", "eloquent"
    |
    */

    "providers" => [
        "users" => [
            "driver" => "eloquent",
            "model"  => AppUser::class,
        ],
    ],

    /*
    |--------------------------------------------------------------------------
    | Resetting Passwords
    |--------------------------------------------------------------------------
    |
    | Here you may set the options for resetting passwords including the view
    | that is your password reset e-mail. You may also set the name of the
    | table that maintains all of the reset tokens for your application.
    |
    | You may specify multiple password reset configurations if you have more
    | than one user table or model in the application and you want to have
    | separate password reset settings based on the specific user types.
    |
    | The expire time is the number of minutes that the reset token should be
    | considered valid. This security feature keeps tokens short-lived so
    | they have less time to be guessed. You may change this as needed.
    |
    */

    "passwords" => [
        //
    ],

];

最后,因为 JWT 协议需要用到 secret,所以需要生成一个 secret:

php artisan jwt:secret

使用 jwt-auth

1. 更新 User Model

继承 TymonJWTAuthContractsJWTSubject:

getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}

2. 写一个 Login 方法,验证登陆信息,并返回 token 回客户端:

// 路由
$router->post("/auth/login", "AuthController@postLogin");

postLogin 方法:

jwt = $jwt;
    }

    public function postLogin(Request $request)
    {
        if (! $token = $this->jwt->attempt($request->only("email", "password"))) {
            return response()->json(["user_not_found"], 404);
        }

        return response()->json(compact("token"));
    }
}

可以请求试试了,用 Postman 跑跑:

有了 token 了。我们就可以用来测试,看能不能认证成功,获取用户信息。

3. 使用 token 获取用户信息

// 使用 auth:api 中间件
$router->group(["middleware" => "auth:api"], function($router)
{
    $router->get("/test", "ExampleController@getUser");
});

只要验证通过,就可以利用 Auth:user()方法获取用户信息了。

public function getUser(Request $request) {
        return response()->json(["user" => Auth::user()]);
    }

对照数据库:

以后只要在请求的 headers 中加入 token 信息即可,完美实现用户认证。

想了解有关 Lumen 的认证相关内容,可以参考上一篇文章《学习 Lumen 用户认证 (一)》https://mp.weixin.qq.com/s/KVUQE2DUetNB2kqxHs0VDg

也可以参考 Lumen 官网
https://lumen.laravel-china.o...

总结

对获取到 token 值 (eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vZGVtby5hcHAvYXV0aC9sb2dpbiIsImlhdCI6MTUxMDQ3NTQ5MiwiZXhwIjoxNTEwNDc5MDkyLCJuYmYiOjE1MTA0NzU0OTIsImp0aSI6Imx3UFpSMTN0MlV5eXRib1oiLCJzdWIiOjEsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.YTvsiO9MT3VgPZiI03v2sVEIsGLj8AUwJiDuXvCAvHI) 仔细观察,就会发现中间是由两个「.」来合并三段信息的。

下一步我们就来研究研究 JWT 的原理和也可以自己动手写个基于 JWT 的 Lumen 认证插件出来。

「未完待续」


coding01 期待您继续关注


也很感谢您能看到这了

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/26080.html

相关文章

  • Lumen用户认证JWT,源码解读

    摘要:如何做用户认证根据文档描述,提供用户认证的接口,他的核心是看守器和提供器,看守器定义怎么认证用户,提供器定义怎么检索用户。 最近的一个PHP项目,上一个项目是采用ThinkPHP来弄的,因为很早就听说过Laravel的大名,所以进了Laravel的官网,意外发现了Lumen,正好我项目是提供API的,所以选择了Lumen,因为是Laravel的精简版,看了几天的Laravel文档,也总...

    AZmake 评论0 收藏0
  • Laravel使用JWT来创建用户认证API

    摘要:本文来自原文链接欢迎作客我们的学习群这个例子将引导你在中使用来创建用户登录和注册的。是的简称,可以帮助我们创建用户认证,以此连接前后端。 本文来自pilishen.com----原文链接; 欢迎作客我们的php&Laravel学习群:109256050 这个例子将引导你在laravel中使用JWT来创建用户登录和注册的API。JWT是Json Web Token的简称,可以帮助我们创建...

    zzbo 评论0 收藏0
  • 学习 Lumen 用户认证 (一)

    摘要:在开发中,用户认证是核心,是数据是否有保障的前提,目前主要有两种常用方式进行用户认证和。附是为了在网络应用环境间传递声明而执行的一种基于的开放标准。 好久没写 PHP 代码了,尤其是 Lumen,我是 Lumen 的忠实用户,自从面世开始,我就将 Lumen 作为我 API 的主要框架使用。 但说到 API,不得不说的一个概念:「前后端分离」,现在越来越多的团队都采用前后端分离,彻底解...

    wangzy2019 评论0 收藏0
  • Laravel 5.5 使用 Jwt-Auth 实现 API 用户认证以及无痛刷新访问令牌

    摘要:默认的时间为周。大概意思就是如果用户有一个,那么他可以带着他的过来领取新的,直到周的时间后,他便无法继续刷新了,需要重新登录。指定在刷新令牌时要保留的声明密钥。为了使令牌无效,您必须启用黑名单。指定用于对用户进行身份验证的提供程序。 showImg(https://segmentfault.com/img/remote/1460000012606251?w=1920&h=1280); ...

    xavier 评论0 收藏0
  • laravel使用JWT做API认证

    摘要:最近项目做认证,最终技术选型决定使用,项目框架使用的是,使用有比较方便使用的开源包。使用安装,使用的框架版本为,最新稳定版本为。 最近项目做API认证,最终技术选型决定使用JWT,项目框架使用的是laravel,laravel使用JWT有比较方便使用的开源包:jwt-auth。 使用composer安装jwt-auth,laravel使用的框架版本为5.0,jwt-auth最新稳定版本...

    SexySix 评论0 收藏0

发表评论

0条评论

姘存按

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<