使用Laravel Passport的注意事项(laravel,passport,编程语言)

时间:2024-05-02 09:25:30 作者 : 石家庄SEO 分类 : 编程语言
  • TAG :

下面由Laravel教程栏目给大家分享Laravel Passport 踩坑日记,希望对需要的朋友有所帮助!

使用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

publicfunctionregister(Request$request){$validator=$this->validator($request->all());if($validator->fails()){returnresponse()->json($validator->errors());}event(newRegistered($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');returnRoute::dispatch($proxy);}

执行,获得返回

{"token_type":"Bearer","expires_in":1296000,"access_token":"xxx","refresh_token":"xxx"}

完美解决。

坑3:我想要使用手机号登录

Passport 其实已经提供了动态修改用户登录的接口,只不过没有在文档里写出来
解决方案:
在你的 User Model 里增加如下方法

publicfunctionfindForPassport($login){returnUser::orWhere('email',$login)->orWhere('mobile',$login)->first();}
坑4: 当使用错误的 token 时, passport 总会跳转到 login 方法

查看源码发现 passport 用的是 web auth 中间件,难怪如此
在你的请求头里增加 Accept:application/json ,问题解决
例如:
使用Laravel Passport的注意事项

 </div> <div class="zixun-tj-product adv-bottom"></div> </div> </div> <div class="prve-next-news">
本文:使用Laravel Passport的注意事项的详细内容,希望对您有所帮助,信息来源于网络。
上一篇:ThinkPHP验证码不显示的解决方法下一篇:

2 人围观 / 0 条评论 ↓快速评论↓

(必须)

(必须,保密)

阿狸1 阿狸2 阿狸3 阿狸4 阿狸5 阿狸6 阿狸7 阿狸8 阿狸9 阿狸10 阿狸11 阿狸12 阿狸13 阿狸14 阿狸15 阿狸16 阿狸17 阿狸18