laravel+jwt-auth 太过爱你忘了你带给我的痛 2022-01-31 14:49 251阅读 0赞 ## guard 准备知识 ## 这部分是 laravel guard 的知识 我们在 config/auth 中设置了不同的 guard 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'jwt', 'provider' => 'users', ], ], \\Auth::guard ('api') 意思是使用 api guard,根据配置使用的 driver 是 jwt,provider 是 users。 driver jwt 在 jwt-auth 这个扩展中定义了 `vendor/tymon/jwt-auth/src/Providers/AbstractServiceProvider.php` ` Auth::guard() ` 用的最多的就是 API 用户登录注册这块了额。 <table> <thead> <tr> <th>Contract</th> <th>References Facade</th> </tr> </thead> <tbody> <tr> <td><a href="https://github.com/illuminate/contracts/blob/5.8/Auth/Guard.php" rel="nofollow">Illuminate\Contracts\Auth\Guard</a></td> <td><code> Auth::guard() </code></td> </tr> <tr> <td><a href="https://github.com/illuminate/contracts/blob/5.8/Auth/StatefulGuard.php" rel="nofollow">Illuminate\Contracts\Auth\StatefulGuard</a></td> <td>~</td> </tr> </tbody> </table> ## 访问指定看守器实例-登录 ## [文档][Link 1] <?php namespace App\Http\Controllers\Api; use App\Http\Requests\Api\AuthorizationRequest; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; class AuthorizationsController extends Controller { // 用户登录 public function store(AuthorizationRequest $request) { $username = $request->username; filter_var($username, FILTER_VALIDATE_EMAIL) ? $credentials['email'] = $username : $credentials['phone'] = $username; $credentials['password'] = $request->password; if (!$token = Auth::guard('api')->attempt($credentials)) { return $this->response->errorUnauthorized('用户名或密码错误'); } return $this->respondWithToken($token)->setStatusCode(201); } // 刷新 token public function update() { $token = Auth::guard('api')->refresh(); return $this->respondWithToken($token); } // 删除 token public function destroy() { Auth::guard('api')->logout(); return $this->response->noContent(); } protected function respondWithToken($token) { return $this->response->array([ 'access_token' => $token, 'token_type' => 'Bearer', 'expires_in' => Auth::guard('api')->factory()->getTTL() * 60, ]); } } 代码讲解: * ` $token = Auth::guard('api')->attempt($credentials) ` // 访问指定看守器实例 相当于【登录】 * ` Auth::guard('api')->refresh(); ` // 在前端实现无感刷新 token, 达到长期登录的目的吧 * ` Auth::guard('api')->logout(); ` // 退出当前登录用户 * ` Auth::guard('api')->factory()->getTTL() * 60 ` // 设置 token 过期的时间 ## 常见用法 ## 1. 为用户生成 ` token `, 通过这个 ` token ` 可以获取用户信息 ` ` Auth::guard('api')->fromUser($user) 2. 为 ` token ` 设置有效期 Auth::guard('api')->factory()->getTTL() * 60 这两个知识点在用户注册的时候将会非常有用。 return $this->response->item($user, new UserTransformer()) ->setMeta([ 'access_token' => Auth::guard('api')->fromUser($user), // 为 user 生成 token 'token_type' => 'Bearer', 'expires_in' => Auth::guard('api')->factory()->getTTL() * 60, // 设置 60 分钟后过期 ]) ->setStatusCode(201);1234567 3. 获取当前登录用户的 id Auth::guard('api')->id();1 3. 获取当前登录用户的 信息 Auth::guard('api')->user(); [Link 1]: https://learnku.com/docs/laravel/5.8/authentication/3906#b7bfe1
还没有评论,来说两句吧...