钱包农场 API 开发手记 四 JWT
2018-04-03 00:00
309 查看
安装 jwt-auth
composer require tymon/jwt-auth:1.0.0-rc.1 php artisan jwt:secret
config/auth.php,将 api guard 的 driver 改为 jwt
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ], ],
config/api.php,auth 中增加 JWT 相关的配置
'auth' => [ 'jwt' => 'Dingo\Api\Auth\Provider\JWT', ],
app\Models\User.php 实现
Tymon\JWTAuth\Contracts\JWTSubject接口,并实现接口的两个方法 getJWTIdentifier() 和 getJWTCustomClaims()。
public function getJWTIdentifier() { return $this->getKey(); } public function getJWTCustomClaims() { return []; }
tinker测试
$user = App\User::first(); Auth::guard('api')->fromUser($user);
用户登录
路由
/ 登录 $api->post('auth', 'AuthController@store') ->name('api.auth.store');
请求验证类
php artisan make:request Api/AuthRequest
return [ 'cellphone' => 'required|regex:/^1[3456789]\d{9}$/', 'code' => 'required|string|min:6', ];
控制器
public function update() { $token = Auth::guard('api')->refresh(); return $this->respWithToken($token)->setStatusCode(201);; } public function destroy() { Auth::guard('api')->logout(); return $this->response->noContent(); }
第三方登录修改
修改 AuthController.php. . $token = Auth::guard('api')->fromUser($user); return $this->respWithToken($token)->setStatusCode(201); } /** * 登录返回封装 * * @param $token * @return mixed */ protected function respWithToken($token) { return $this->response->array([ 'access_token' => $token, 'token_type' => 'Bearer', 'expires_in' => Auth::guard('api')->factory()->getTTL() * 60 ]); }
刷新/删除 token
路由
// 刷新token $api->put('auth/current', 'AuthController@update') ->name('api.auth.update'); // 删除token $api->delete('auth/current', 'AuthController@destroy') ->name('api.auth.destroy');
控制器
public function update() { $token = Auth::guard('api')->refresh(); return $this->respWithToken($token); } public function destroy() { Auth::guard('api')->logout(); return $this->response->noContent(); }
相关文章推荐
- 钱包农场 API 开发手记 一 开篇
- 钱包农场 API 开发手记 十三 收货地址
- 钱包农场 API 开发手记 三 微信登录
- 钱包农场 API 开发手记 七 绑定手机
- 钱包农场 API 开发手记 六 更新用户信息
- 钱包农场 API 开发手记 十二 文章
- 钱包农场 API 开发手记 八 土豆
- 钱包农场 API 开发手记 十一 订单
- 钱包农场 API 开发手记 十 商品
- 钱包农场 API 开发手记 九 金豆
- 钱包农场 API 开发手记 二 SMS
- Lumen上使用Dingo/Api做API开发时用JWT-Auth做认证的实现
- 微信小程序开发手记之六:API
- TWS API 开发手记——连接到TWS平台
- WO+开放平台:API调用开发手记(话费计费接口2.0)
- Laravel 5 开发API(Dingo Api + JWT)
- Lumen上使用Dingo/Api做API开发时用JWT-Auth做认证的实现
- WO+开放平台:API调用开发手记(话费计费接口2.0)
- WO+开放平台:API调用开发手记(关于签名字段)
- 关于上一篇日志《TWS API 开发手记——连接到TWS平台》的修正