摘要:看到社區(qū)常有人問(wèn)用于密碼驗(yàn)證方式來(lái)獲取的問(wèn)題,剛好我最近一個(gè)項(xiàng)目使用,也是使用的密碼授權(quán)來(lái)做驗(yàn)證,對(duì)于如何做登錄登出,以及多賬號(hào)系統(tǒng)的認(rèn)證等常用場(chǎng)景做一下簡(jiǎn)單的使用小總結(jié)。
看到Laravel-China社區(qū)常有人問(wèn)Laravel Passport用于密碼驗(yàn)證方式來(lái)獲取Token的問(wèn)題,剛好我最近一個(gè)API項(xiàng)目使用Laravel Dingo Api+Passport,也是使用Oauth2 的"grant_type" => "password"密碼授權(quán)來(lái)做Auth驗(yàn)證,對(duì)于如何做登錄登出,以及多賬號(hào)系統(tǒng)的認(rèn)證等常用場(chǎng)景做一下簡(jiǎn)單的使用小總結(jié)。
基本配置基本安裝配置主要參照官方文檔,具體不詳細(xì)說(shuō),列出關(guān)鍵代碼段
config/auth.php
"guards" => [ "api" => [ "driver" => "passport", "provider" => "users", ], ], "providers" => [ "users" => [ "driver" => "eloquent", "model" => AppModelsUser::class ], ],
Providers/AuthServiceProvider.php
public function boot() { $this->registerPolicies(); //默認(rèn)令牌發(fā)放的有效期是永久 //Passport::tokensExpireIn(Carbon::now()->addDays(2)); //Passport::refreshTokensExpireIn(Carbon::now()->addDays(4)); Passport::routes(function (RouteRegistrar $router) { //對(duì)于密碼授權(quán)的方式只要這幾個(gè)路由就可以了 config(["auth.guards.api.provider" => "users"]); $router->forAccessTokens(); }); }
Middleware/AuthenticateApi.php 自定義中間件返回
auth->guard("api")->check()) { return $this->auth->shouldUse("api"); } throw new UnauthorizedHttpException("", "Unauthenticated"); } }
App/Http/Kernel.php
/** * The application"s route middleware. * * These middleware may be assigned to groups or used individually. * * @var array */ protected $routeMiddleware = [ "api-auth" => AuthenticateApi::class, ...... ]; }賬號(hào)驗(yàn)證字段不止郵箱
對(duì)于賬號(hào)驗(yàn)證不止是數(shù)據(jù)表中的emial字段,還可能是用戶名或者手機(jī)號(hào)字段只需要在User模型中添加findForPassport方法,示例代碼如下:
AppModelsUsers
class User extends Authenticatable implements Transformable { use TransformableTrait, HasApiTokens, SoftDeletes; public function findForPassport($login) { return $this->orWhere("email", $login)->orWhere("phone", $login)->first(); } }客戶端獲取access_token請(qǐng)求只傳用戶名和密碼
對(duì)于密碼授權(quán)的方式需要提交的參數(shù)如下:
$response = $http->post("http://your-app.com/oauth/token", [ "form_params" => [ "grant_type" => "password", "client_id" => "client-id", "client_secret" => "client-secret", "username" => "[email protected]", "password" => "my-password", "scope" => "", ], ]);
但是客戶端請(qǐng)求的時(shí)候不想把grant_type,client_id,client_secret,scope放到請(qǐng)求參數(shù)中或者暴露給客戶端,只像JWT一樣只發(fā)送username和password 怎么辦?很簡(jiǎn)單我們只要將不需要請(qǐng)求的放到配置文件中,然后客戶端請(qǐng)求用戶名密碼以后我們?cè)傧?b>oauth/token發(fā)送請(qǐng)求帶上相關(guān)的配置就可以了。
.env.php
OAUTH_GRANT_TYPE=password OAUTH_CLIENT_ID=1 OAUTH_CLIENT_SECRET=EvE4UPGc25TjXwv9Lmk432lpp7Uzb8G4fNJsyJ83 OAUTH_SCOPE=*
config/passport.php 當(dāng)然該配置你可以配置多個(gè)client
return [ "grant_type" => env("OAUTH_GRANT_TYPE"), "client_id" => env("OAUTH_CLIENT_ID"), "client_secret" => env("OAUTH_CLIENT_SECRET"), "scope" => env("OAUTH_SCOPE", "*"), ];
LoginController.php的示例代碼如下,因?yàn)橛昧?b>Dingo Api配置了api前綴,所以請(qǐng)求/api/oauth/token
/** * 獲取登錄TOKEN * @param LoginRequest $request * @return IlluminateHttpJsonResponse */ public function token(LoginRequest $request) { $username = $request->get("username"); $user = User::orWhere("email", $username)->orWhere("phone", $username)->first(); if ($user && ($user->status == 0)) { throw new UnauthorizedHttpException("", "賬號(hào)已被禁用"); } $client = new Client(); try { $request = $client->request("POST", request()->root() . "/api/oauth/token", [ "form_params" => config("passport") + $request->only(array_keys($request->rules())) ]); } catch (RequestException $e) { throw new UnauthorizedHttpException("", "賬號(hào)驗(yàn)證失敗"); } if ($request->getStatusCode() == 401) { throw new UnauthorizedHttpException("", "賬號(hào)驗(yàn)證失敗"); } return response()->json($request->getBody()->getContents()); }退出登錄并清除Token
對(duì)于客戶端退出后并清除記錄在oauth_access_tokens表中的記錄,示例代碼如下:
/** * 退出登錄 */ public function logout() { if (Auth::guard("api")->check()) { Auth::guard("api")->user()->token()->delete(); } return response()->json(["message" => "登出成功", "status_code" => 200, "data" => null]); }根據(jù)用戶ID認(rèn)證用戶
app("auth")->guard("api")->setUser(User::find($userId));多用戶表(多Auth)認(rèn)證
比如針對(duì)客戶表和管理員表分別做Auth認(rèn)證的情況,也列出關(guān)鍵代碼段:
"guards" => [ "api" => [ "driver" => "passport", "provider" => "users", ], "admin_api" => [ "driver" => "passport", "provider" => "admin_users", ], ], "providers" => [ "users" => [ "driver" => "eloquent", "model" => AppModelsUser::class ], "admin_users" => [ "driver" => "eloquent", "model" => AppModelsAdminUser::class ], ],
新建一個(gè)PasspordAdminServiceProvider來(lái)實(shí)現(xiàn)我們自己的PasswordGrant,別忘了添加到config/app.php的providers配置段中
AppProviders/PasspordAdminServiceProvider
app->make(AdminUserPassportRepository::class), $this->app->make(LaravelPassportBridgeRefreshTokenRepository::class) ); $grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn()); return $grant; } }
新建AdminUserPassportRepository,Password的驗(yàn)證主要通過(guò)getUserEntityByUserCredentials,它讀取配置的guards對(duì)應(yīng)的provider來(lái)做認(rèn)證,我們重寫該方法,通過(guò)傳遞一個(gè)參數(shù)來(lái)告訴它我們要用哪個(gè)guard來(lái)做客戶端認(rèn)證
get("guard") ?: "api";//其實(shí)關(guān)鍵的就在這里,就是通過(guò)傳遞一個(gè)guard參數(shù)來(lái)告訴它我們是使用api還是admin_api provider來(lái)做認(rèn)證 $provider = config("auth.guards.{$guard}.provider"); if (is_null($model = config("auth.providers.{$provider}.model"))) { throw new RuntimeException("Unable to determine user model from configuration."); } if (method_exists($model, "findForPassport")) { $user = (new $model)->findForPassport($username); } else { $user = (new $model)->where("email", $username)->first(); } if (!$user) { return; } elseif (method_exists($user, "validateForPassportPasswordGrant")) { if (!$user->validateForPassportPasswordGrant($password)) { return; } } elseif (!$this->hasher->check($password, $user->password)) { return; } return new User($user->getAuthIdentifier()); } }
登錄和單用戶系統(tǒng)一樣,只是在請(qǐng)求oauth/token的時(shí)候帶上guard參數(shù),示例代碼如下:
Admin/Controllers/Auth/LoginController.php
middleware("guest")->except("logout"); } /** * 獲取登錄TOKEN * @param LoginRequest $request * @return IlluminateHttpJsonResponse */ public function token(LoginRequest $request) { $username = $request->get("username"); $user = AdminUser::orWhere("email", $username)->orWhere("phone", $username)->first(); if ($user && ($user->status == 0)) { throw new UnauthorizedHttpException("", "賬號(hào)已被禁用"); } $client = new Client(); try { $request = $client->request("POST", request()->root() . "/api/oauth/token", [ "form_params" => config("passport") + $request->only(array_keys($request->rules())) + ["guard" => "admin_api"] ]); } catch (RequestException $e) { throw new UnauthorizedHttpException("", "賬號(hào)驗(yàn)證失敗"); } if ($request->getStatusCode() == 401) { throw new UnauthorizedHttpException("", "賬號(hào)驗(yàn)證失敗"); } return response()->json($request->getBody()->getContents()); } /** * 退出登錄 */ public function logout() { if (Auth::guard("admin_api")->check()) { Auth::guard("admin_api")->user()->token()->delete(); } return response()->json(["message" => "登出成功", "status_code" => 200, "data" => null]); } }
轉(zhuǎn)載請(qǐng)注明:?轉(zhuǎn)載自Ryan是菜鳥 | LNMP技術(shù)棧筆記
如果覺(jué)得本篇文章對(duì)您十分有益,何不 打賞一下
本文鏈接地址:?Laravel Passport API 認(rèn)證使用小結(jié)
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/25579.html
showImg(https://segmentfault.com/img/bV6aHV?w=1280&h=800); 社區(qū)優(yōu)秀文章 Laravel 5.5+passport 放棄 dingo 開(kāi)發(fā) API 實(shí)戰(zhàn),讓 API 開(kāi)發(fā)更省心 - 自造車輪。 API 文檔神器 Swagger 介紹及在 PHP 項(xiàng)目中使用 - API 文檔撰寫方案 推薦 Laravel API 項(xiàng)目必須使用的 8 個(gè)...
摘要:在本教程中,我們將了解如何在應(yīng)用中使用認(rèn)證。當(dāng)用戶通過(guò)登錄時(shí),會(huì)生成令牌并將其發(fā)送給用戶,該用戶可用于身份驗(yàn)證。提供,可以毫無(wú)困難地使用認(rèn)證。服務(wù)提供者我們使用的最新版本,它可以使用包發(fā)現(xiàn)并自動(dòng)注冊(cè)服務(wù)。 showImg(https://segmentfault.com/img/remote/1460000019095408?w=1000&h=526); 在本教程中,我們將了解如何在 ...
摘要:第一部分安裝第一步使用安裝第二步服務(wù)提供器使用框架注冊(cè)自己的數(shù)據(jù)庫(kù)遷移目錄,因此在注冊(cè)提供器后,就應(yīng)該運(yùn)行的遷移命令來(lái)自動(dòng)創(chuàng)建存儲(chǔ)客戶端和令牌的數(shù)據(jù)表第三步接下來(lái),運(yùn)行命令來(lái)創(chuàng)建生成安全訪問(wèn)令牌時(shí)所需的加密密鑰,同時(shí),這條命令也會(huì)創(chuàng)建用于生 第一部分 安裝Passport(laravel/passport) 第一步. 使用 Composer 安裝 Passport :composer...
摘要:使用進(jìn)行測(cè)試注冊(cè)接口,注冊(cè)成功后返回與用戶名登錄接口詳情接口參考了簡(jiǎn)書浪來(lái)了的認(rèn)證應(yīng)用實(shí)戰(zhàn) 安裝larave laravel new passport_demo cd passport_demo && composer install 將 .env 中數(shù)據(jù)庫(kù)配置修改為自己的數(shù)據(jù)庫(kù)配置 DB_DATABASE=homestead DB_USERNAME=homestead DB_P...
摘要:本文來(lái)自原文鏈接歡迎作客我們的學(xué)習(xí)群比如說(shuō)你要給你的手機(jī)用戶創(chuàng)建,使用的是你已有的系統(tǒng)里的數(shù)據(jù)庫(kù),尤其是用戶數(shù)據(jù)。 本文來(lái)自pilishen.com----原文鏈接; 歡迎作客我們的php&Laravel學(xué)習(xí)群:109256050 比如說(shuō)你要給你的手機(jī)APP用戶創(chuàng)建API,使用的是你已有的Laravel系統(tǒng)里的數(shù)據(jù)庫(kù),尤其是用戶數(shù)據(jù)?,F(xiàn)在我們來(lái)看一下,這里使用的是Laravel Pas...
閱讀 1845·2021-09-22 15:23
閱讀 3278·2021-09-04 16:45
閱讀 1902·2021-07-29 14:49
閱讀 2779·2019-08-30 15:44
閱讀 1529·2019-08-29 16:36
閱讀 1048·2019-08-29 11:03
閱讀 1520·2019-08-26 13:53
閱讀 516·2019-08-26 11:57