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

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

namespace App\Providers;

use App\User;

use Illuminate\Support\Facades\Gate;

use Illuminate\Support\ServiceProvider;

class AuthServiceProvider extends ServiceProvider

{

/**

* Register any application services.

*

* @return void

*/

public function register()

{

//

}

/**

* Boot the authentication services for the application.

*

* @return void

*/

public function boot()

{

// Here you may define how you wish users to be authenticated for your Lumen

// application. The callback which receives the incoming request instance

// should return either a User instance or null. You're free to obtain

// the User instance via an API token or any other method necessary.

$this->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 最多的那个拿来研究研究。

1460000011971346?w=1718&h=1350

tymondesigns/jwt-auth

JSON Web Token Authentication for Laravel & Lumen

1460000011971347?w=885&h=367

安装 jwt-auth

通过 Composer 安装:

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

1460000011971348?w=1620&h=456

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

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

require_once __DIR__.'/../vendor/autoload.php';

try {

(new Dotenv\Dotenv(__DIR__.'/../'))->load();

} catch (Dotenv\Exception\InvalidPathException $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 Laravel\Lumen\Application(

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(

Illuminate\Contracts\Debug\ExceptionHandler::class,

App\Exceptions\Handler::class

);

$app->singleton(

Illuminate\Contracts\Console\Kernel::class,

App\Console\Kernel::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([

// App\Http\Middleware\ExampleMiddleware::class

// ]);

// 增加 auth 中间件

$app->routeMiddleware([

'auth' => App\Http\Middleware\Authenticate::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(App\Providers\AppServiceProvider::class);

$app->register(App\Providers\AuthServiceProvider::class);

// $app->register(App\Providers\EventServiceProvider::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' => 'App\Http\Controllers',

], function ($router) {

require __DIR__.'/../routes/web.php';

});

return $app;

然后在 AppServiceProvider 中注册 LumenServiceProvider:

$this->app->register(\Tymon\JWTAuth\Providers\LumenServiceProvider::class);

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

return [

/*

|--------------------------------------------------------------------------

| Authentication Defaults

|--------------------------------------------------------------------------

|

| This option controls the default authentication "guard" and password

| reset options for your application. You may change these defaults

| as required, but they're a perfect start for most applications.

|

*/

'defaults' => [

'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' => \App\User::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

1460000011971349?w=1698&h=124

使用 jwt-auth

1. 更新 User Model

继承 TymonJWTAuthContractsJWTSubject:

namespace App;

use Illuminate\Auth\Authenticatable;

use Laravel\Lumen\Auth\Authorizable;

use Illuminate\Database\Eloquent\Model;

use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;

use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject

{

use Authenticatable, Authorizable;

/**

* The attributes that are mass assignable.

*

* @var array

*/

protected $fillable = [

'name', 'email',

];

/**

* The attributes excluded from the model's JSON form.

*

* @var array

*/

protected $hidden = [

'password',

];

/**

* Get the identifier that will be stored in the subject claim of the JWT.

*

* @return mixed

*/

public function getJWTIdentifier()

{

return $this->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 方法:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Tymon\JWTAuth\JWTAuth;

class AuthController extends Controller

{

protected $jwt;

public function __construct(JWTAuth $jwt)

{

$this->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 跑跑:

1460000011971350?w=2126&h=962

有了 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()]);

}

1460000011971351?w=1640&h=884

对照数据库:

1460000011971352?w=1974&h=266

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

总结

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

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

「未完待续」

coding01 期待您继续关注

1460000011209512

也很感谢您能看到这了

1460000011768053?w=1152&h=1152

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Lumen是一个基于Laravel框架的微型PHP框架,它可以用于构建轻量级的API服务。而Dingo是一个在Laravel框架上构建API的工具包。JWT(JSON Web Token)是一种用于进行身份验证和授权的开放标准。 在使用Lumen结合Dingo和JWT进行开发时,需要先安装Lumen服务提供者、JWT和Dingo的组件。可以使用Composer来管理这些依赖。确保你的电脑上安装了Composer。 在Lumen中,你可以使用控制器来处理请求。引用是一个示例UserController。在这个控制器中,我们注入了JWTAuth实例,并使用它来处理用户的登录请求。其中,我们首先获取请求中的参数,然后使用这些参数进行条件查询。如果登录认证成功,我们会返回一个包含JWT令牌的JSON响应。 对于跨域问题,你可以使用palanik/lumen-cors来解决。引用提供了安装和配置palanik/lumen-cors的方法。你需要通过Composer来安装该组件,并在bootstrap/app.php文件中添加cors路由中间件。 以上就是关于Lumen、Dingo和JWT的一些基本信息和配置方法。如果你有关于它们的更具体的问题,请告诉我。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Lumen 配合 JWT + Dingo 开发流程](https://blog.csdn.net/qq_44149053/article/details/89444892)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *3* [lumen+dingo+jwt搭建api系统](https://blog.csdn.net/Chenlevin/article/details/111830096)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值