The following is the Laravel tutorial column to share with you the Laravel Passport pit diary, I hope it will be helpful to friends in need!
Most previous projects used DingoAPI JWT-auth to implement API authentication. Although Laravel released Passport very early, it has not paid much attention to it.
I played Passport today. Although I encountered a lot of pitfalls, it is still very easy to use~
Solution:
Redefine it in your
AuthServiceProvider:
Passport::routes(function (RouteRegistrar $router) { $router->forAccessTokens(); }, ['prefix' => 'api']);
when registering an account?
JWTAuth::fromUser($user); can be easily generated
token, but there seems to be no ready-made method in Passport.
Solution:
After registering the account, actively request
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" }
Solution:
Add the following method to your User Model
public function findForPassport($login) { return User::orWhere('email', $login)->orWhere('mobile', $login)->first(); }
, passport will always jump to the login method
web
auth middleware, no wonder
Add
Accept: in your request header application/json, problem solving
For example:
The above is the detailed content of Share Laravel Passport Pitfall Diary. For more information, please follow other related articles on the PHP Chinese website!