摘要:在開(kāi)發(fā)中,用戶認(rèn)證是核心,是數(shù)據(jù)是否有保障的前提,目前主要有兩種常用方式進(jìn)行用戶認(rèn)證和。為了學(xué)習(xí)在中的使用,最好的辦法就是在程序員同志網(wǎng)搜索有關(guān)插件,找個(gè)最多的那個(gè)拿來(lái)研究研究。
通過(guò)上一篇《學(xué)習(xí) Lumen 用戶認(rèn)證 (一)》https://mp.weixin.qq.com/s/KVUQE2DUetNB2kqxHs0VDg的學(xué)習(xí),大致懂了 Lumen 的用戶認(rèn)證主要使用 「api」的方式,來(lái)默認(rèn)進(jìn)行用戶認(rèn)證:
app["auth"]->viaRequest("api", function ($request) { if ($request->input("api_token")) { return User::where("api_token", $request->input("api_token"))->first(); } }); } }
當(dāng)然在實(shí)際開(kāi)發(fā)中,我們不能只是簡(jiǎn)單的獲取 api_token直接關(guān)聯(lián)數(shù)據(jù)庫(kù)查找用戶信息。
在 API 開(kāi)發(fā)中,用戶認(rèn)證是核心,是數(shù)據(jù)是否有保障的前提,目前主要有兩種常用方式進(jìn)行用戶認(rèn)證: JWT 和 OAuth2。
本文將簡(jiǎn)要說(shuō)說(shuō)如何利用 JWT 來(lái)進(jìn)行用戶認(rèn)證
JWTJson web token (JWT), 是為了在網(wǎng)絡(luò)應(yīng)用環(huán)境間傳遞聲明而執(zhí)行的一種基于JSON 的開(kāi)放標(biāo)準(zhǔn) (RFC 7519)。該 token 被設(shè)計(jì)為緊湊且安全的,特別適用于分布式站點(diǎn)的單點(diǎn)登錄(SSO)場(chǎng)景。JWT 的聲明一般被用來(lái)在身份提供者和服務(wù)提供者間傳遞被認(rèn)證的用戶身份信息,以便于從資源服務(wù)器獲取資源,也可以增加一些額外的其它業(yè)務(wù)邏輯所必須的聲明信息,該 token 也可直接被用于認(rèn)證,也可被加密。
關(guān)于 JWT 更具體的介紹,相信網(wǎng)上有很多帖子和文章值得參考,這里先不闡述了。
為了學(xué)習(xí) JWT 在 Lumen 中的使用,最好的辦法就是在「程序員同志網(wǎng) —— GitHub」搜索有關(guān)插件,找個(gè) stars 最多的那個(gè)拿來(lái)研究研究。
tymondesigns/jwt-auth安裝 jwt-authJSON Web Token Authentication for Laravel & Lumen
通過(guò) Composer 安裝:
composer require tymon/jwt-auth:"^1.0@dev"
注: 0.5.* 版本未對(duì) Lumen 專門做封裝
將 $app->withFacades() 和 auth 認(rèn)證相關(guān)的注釋去掉:
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__."/../") ); // 取消注釋,這樣就可以通過(guò) Auth::user(),獲取當(dāng)前授權(quán)用戶 $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 中注冊(cè) LumenServiceProvider:
$this->app->register(TymonJWTAuthProvidersLumenServiceProvider::class);
在 Lumen 項(xiàng)目中,默認(rèn)沒(méi)有 config 文件夾,需要在項(xiàng)目根目錄創(chuàng)建,并將 vendor 源代碼中auth.php 復(fù)制出來(lái),同時(shí)將 api 認(rèn)證指定為「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" => [ // ], ];
最后,因?yàn)?JWT 協(xié)議需要用到 secret,所以需要生成一個(gè) 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. 寫(xiě)一個(gè) Login 方法,驗(yàn)證登陸信息,并返回 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")); } }
可以請(qǐng)求試試了,用 Postman 跑跑:
有了 token 了。我們就可以用來(lái)測(cè)試,看能不能認(rèn)證成功,獲取用戶信息。
3. 使用 token 獲取用戶信息
// 使用 auth:api 中間件 $router->group(["middleware" => "auth:api"], function($router) { $router->get("/test", "ExampleController@getUser"); });
只要驗(yàn)證通過(guò),就可以利用 Auth:user()方法獲取用戶信息了。
public function getUser(Request $request) { return response()->json(["user" => Auth::user()]); }
對(duì)照數(shù)據(jù)庫(kù):
以后只要在請(qǐng)求的 headers 中加入 token 信息即可,完美實(shí)現(xiàn)用戶認(rèn)證。
總結(jié)想了解有關(guān) Lumen 的認(rèn)證相關(guān)內(nèi)容,可以參考上一篇文章《學(xué)習(xí) Lumen 用戶認(rèn)證 (一)》https://mp.weixin.qq.com/s/KVUQE2DUetNB2kqxHs0VDg
也可以參考 Lumen 官網(wǎng)
https://lumen.laravel-china.o...
對(duì)獲取到 token 值 (eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOi8vZGVtby5hcHAvYXV0aC9sb2dpbiIsImlhdCI6MTUxMDQ3NTQ5MiwiZXhwIjoxNTEwNDc5MDkyLCJuYmYiOjE1MTA0NzU0OTIsImp0aSI6Imx3UFpSMTN0MlV5eXRib1oiLCJzdWIiOjEsInBydiI6Ijg3ZTBhZjFlZjlmZDE1ODEyZmRlYzk3MTUzYTE0ZTBiMDQ3NTQ2YWEifQ.YTvsiO9MT3VgPZiI03v2sVEIsGLj8AUwJiDuXvCAvHI) 仔細(xì)觀察,就會(huì)發(fā)現(xiàn)中間是由兩個(gè)「.」來(lái)合并三段信息的。
下一步我們就來(lái)研究研究 JWT 的原理和也可以自己動(dòng)手寫(xiě)個(gè)基于 JWT 的 Lumen 認(rèn)證插件出來(lái)。
「未完待續(xù)」
coding01 期待您繼續(xù)關(guān)注
也很感謝您能看到這了
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.hztianpu.com/yun/26080.html
摘要:如何做用戶認(rèn)證根據(jù)文檔描述,提供用戶認(rèn)證的接口,他的核心是看守器和提供器,看守器定義怎么認(rèn)證用戶,提供器定義怎么檢索用戶。 最近的一個(gè)PHP項(xiàng)目,上一個(gè)項(xiàng)目是采用ThinkPHP來(lái)弄的,因?yàn)楹茉缇吐?tīng)說(shuō)過(guò)Laravel的大名,所以進(jìn)了Laravel的官網(wǎng),意外發(fā)現(xiàn)了Lumen,正好我項(xiàng)目是提供API的,所以選擇了Lumen,因?yàn)槭荓aravel的精簡(jiǎn)版,看了幾天的Laravel文檔,也總...
摘要:本文來(lái)自原文鏈接歡迎作客我們的學(xué)習(xí)群這個(gè)例子將引導(dǎo)你在中使用來(lái)創(chuàng)建用戶登錄和注冊(cè)的。是的簡(jiǎn)稱,可以幫助我們創(chuàng)建用戶認(rèn)證,以此連接前后端。 本文來(lái)自pilishen.com----原文鏈接; 歡迎作客我們的php&Laravel學(xué)習(xí)群:109256050 這個(gè)例子將引導(dǎo)你在laravel中使用JWT來(lái)創(chuàng)建用戶登錄和注冊(cè)的API。JWT是Json Web Token的簡(jiǎn)稱,可以幫助我們創(chuàng)建...
摘要:在開(kāi)發(fā)中,用戶認(rèn)證是核心,是數(shù)據(jù)是否有保障的前提,目前主要有兩種常用方式進(jìn)行用戶認(rèn)證和。附是為了在網(wǎng)絡(luò)應(yīng)用環(huán)境間傳遞聲明而執(zhí)行的一種基于的開(kāi)放標(biāo)準(zhǔn)。 好久沒(méi)寫(xiě) PHP 代碼了,尤其是 Lumen,我是 Lumen 的忠實(shí)用戶,自從面世開(kāi)始,我就將 Lumen 作為我 API 的主要框架使用。 但說(shuō)到 API,不得不說(shuō)的一個(gè)概念:「前后端分離」,現(xiàn)在越來(lái)越多的團(tuán)隊(duì)都采用前后端分離,徹底解...
摘要:默認(rèn)的時(shí)間為周。大概意思就是如果用戶有一個(gè),那么他可以帶著他的過(guò)來(lái)領(lǐng)取新的,直到周的時(shí)間后,他便無(wú)法繼續(xù)刷新了,需要重新登錄。指定在刷新令牌時(shí)要保留的聲明密鑰。為了使令牌無(wú)效,您必須啟用黑名單。指定用于對(duì)用戶進(jìn)行身份驗(yàn)證的提供程序。 showImg(https://segmentfault.com/img/remote/1460000012606251?w=1920&h=1280); ...
摘要:最近項(xiàng)目做認(rèn)證,最終技術(shù)選型決定使用,項(xiàng)目框架使用的是,使用有比較方便使用的開(kāi)源包。使用安裝,使用的框架版本為,最新穩(wěn)定版本為。 最近項(xiàng)目做API認(rèn)證,最終技術(shù)選型決定使用JWT,項(xiàng)目框架使用的是laravel,laravel使用JWT有比較方便使用的開(kāi)源包:jwt-auth。 使用composer安裝jwt-auth,laravel使用的框架版本為5.0,jwt-auth最新穩(wěn)定版本...
閱讀 2682·2023-04-25 17:33
閱讀 718·2021-11-23 09:51
閱讀 3040·2021-07-30 15:32
閱讀 1501·2019-08-29 18:40
閱讀 2030·2019-08-28 18:19
閱讀 1529·2019-08-26 13:48
閱讀 2314·2019-08-23 16:48
閱讀 2356·2019-08-23 15:56