下面由laravel教程欄目給大家分享Laravel Passport 踩坑日記,希望對需要的朋友有所幫助!
以前的項目大多使用 dingoapi + jwt-auth 實現的 api 認證,laravel 雖然在很早就出了 passport ,但一直沒有怎么關注。
今天擼了一把 passport ,雖然遇到不少坑,但是趕腳這個東西還是蠻好用的~
坑1:我暫時只想通過賬號密碼獲取 token
Passport 一出生就自帶了很多的路由。。 but,這些東東大部分對我是真的沒用啊
解決方案:
在你的 AuthServiceProvider ?里重新定義:
Passport::routes(function?(RouteRegistrar?$router)?{ ????????????$router->forAccessTokens(); ????????},?['prefix'?=>?'api']);
坑2: 注冊賬號時,如何手動生成 Token ?
jwt-auth 的 JWTAuth::fromUser($user); 可以很簡單的生成token,但是在 Passport 里似乎沒有現成的方法。
解決方案:
注冊完賬號后,再一次主動請求 oauth/token
public?function?register(Request?$request) ????{ ????????$validator?=?$this->validator($request->all()); ????????if?($validator->fails()){ ????????????return?response()->json($validator->errors()); ????????} ????????event(new?Registered($user?=?$this->create($request->all()))); ????????$client?=?DB::table('oauth_clients')->where('password_client',?1)->first(); ????????$request->request->add([ ????????????'username'?=>?$user->email, ????????????'password'?=>?$request->password, ????????????'grant_type'?=>?'password', ????????????'client_id'?=>?$client->id, ????????????'client_secret'?=>?$client->secret, ????????????'scope'?=>?'*' ????????]); ????????$proxy?=?Request::create( ????????????'oauth/token', ????????????'POST' ????????); ????????return?Route::dispatch($proxy); ????}
執行,獲得返回
{ ??"token_type":?"Bearer", ??"expires_in":?1296000, ??"access_token":?"xxx", ??"refresh_token":?"xxx" }
完美解決。
坑3:我想要使用手機號登錄
Passport 其實已經提供了動態修改用戶登錄的接口,只不過沒有在文檔里寫出來
解決方案:
在你的 User Model 里增加如下方法
public?function?findForPassport($login)?{ ????????return?User::orWhere('email',?$login)->orWhere('mobile',?$login)->first(); ????}
坑4: 當使用錯誤的 token 時, passport 總會跳轉到 login 方法
查看源碼發現 passport 用的是 web auth 中間件,難怪如此
在你的請求頭里增加 Accept:application/json ,問題解決
例如:
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END