laravel jwt的基本配置及使用

2019-03-06 10:50:03   php分享记录

  jwt  

laravel jwt的安装使用

  1. jwt的安装

    1. composer require tymon/jwt-auth
  2. config.php中添加服务提供程序

    1. 'providers' => [
    2. ...
    3. Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
    4. ]
  3. 发布配置文件

    1. php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider
  4. 生成密钥

    1. php artisan jwt:secret
  5. 更改用户模型

    1. //倘若不想使用默认的User.php auth模型的话,自己手动新建一个模型,并在auth.php中配置
    2. namespace App\DB;
    3. use Illuminate\Notifications\Notifiable;
    4. use Illuminate\Foundation\Auth\User as Authenticatable;
    5. use Tymon\JWTAuth\Contracts\JWTSubject;
    6. class Staff extends Authenticatable implements JWTSubject
    7. {
    8. protected $table = 'staff';
    9. protected $primaryKey = 'id';
    10. use Notifiable;
    11. public function getJWTIdentifier()
    12. {
    13. return $this->getKey();
    14. // TODO: Implement getJWTIdentifier() method.
    15. }
    16. public function getJWTCustomClaims()
    17. {
    18. return [];
    19. // TODO: Implement getJWTCustomClaims() method.
    20. }
    21. }
  6. 配置auth guard

    1. 'defaults' => [
    2. 'guard' => 'api',
    3. 'passwords' => 'users',
    4. ],
    5. ...
    6. 'guards' => [
    7. 'api' => [
    8. 'driver' => 'jwt',
    9. 'provider' => 'users',
    10. ],
    11. ],
    12. ···
    13. 'providers' => [
    14. 'users' => [
    15. 'driver' => 'eloquent',
    16. 'model' => App\DB\Staff::class,
    17. 'table' =>'user_basic'
    18. ],
    19. ],
  7. 添加路由api.php

    1. Route::group([
    2. 'middleware' => 'api',
    3. 'prefix' => 'auth'
    4. ], function ($router) {
    5. Route::post('login', 'AuthController@login');
    6. Route::post('logout', 'AuthController@logout');
    7. Route::post('refresh', 'AuthController@refresh');
    8. Route::post('me', 'AuthController@me');
    9. });
  8. 创建控制器

    1. php artisan make:controller AuthController
    1. namespace App\Http\Controllers;
    2. use App\DB\Staff;
    3. use Illuminate\Http\Request;
    4. use Illuminate\Support\Facades\Auth;
    5. use Illuminate\Support\Facades\Response;
    6. use Tymon\JWTAuth\Facades\JWTAuth;
    7. class AuthController extends Controller
    8. {
    9. public function __construct()
    10. {
    11. $this->middleware('RefreshToken', ['except' => 'login']);
    12. }
    13. public function login(Request $request)
    14. {
    15. if(\auth()->check()){
    16. //如果有有效token,则先手动失效
    17. \auth()->invalidate();
    18. }
    19. $input = request(['work_num', 'password']);
    20. // 验证规则,由于业务需求,这里我更改了一下登录的用户名,使用手机号码登录
    21. $rules = [
    22. 'work_num' => [
    23. 'required',
    24. ],
    25. 'password' => 'required|numeric',
    26. ];
    27. $messages = [
    28. 'required'=>":attribute不能为空",
    29. 'numeric'=>":attribute必须为数字",
    30. ];
    31. $attributes = [
    32. 'work_num'=>"工号",
    33. 'password'=>"密码"
    34. ];
    35. $validator = \Validator::make($input,$rules,$messages,$attributes);
    36. if($validator->fails()){
    37. $error = $validator->errors()->first();
    38. return response()->json([
    39. 'code'=>"201",
    40. 'error'=>$error
    41. ]);
    42. }
    43. // 验证参数,如果验证失败,则会抛出 ValidationException 的异常
    44. $params = $this->validate($request, $rules);
    45. if ($user = Staff::where(['work_num' => $input['work_num'], 'password' => md5(md5($input['password']))])->first()) {
    46. // $token = JWTAuth::fromUser($user);
    47. $token = auth('api')->login($user);
    48. } else {
    49. return response()->json(['result' => '账号或密码错误.']);
    50. }
    51. return response()->json(
    52. [
    53. 'access_token' => $token,
    54. 'token_type' => 'bearer',
    55. 'expires_in' => auth()->factory()->getTTL() * 60
    56. ]
    57. );
    58. }
    59. public function me(){
    60. $user = \auth('api')->user();
    61. return response()->json(compact('user'));
    62. }
    63. public function logout()
    64. {
    65. \auth()->logout();
    66. return response(['message' => '退出成功']);
    67. }
  9. 中间件

    1. php artisan make:middleware RefreshToken
    1. kernel.php
    2. protected $routeMiddleware=[
    3. ···
    4. 'RefreshToken'=>\App\Http\Middleware\RefreshToken::class
    5. ···
    6. ]
  10. 中间件内容

    1. public function handle($request, Closure $next)
    2. {
    3. $this->checkForToken($request);
    4. try{
    5. if($this->auth->parseToken()->authenticate()){
    6. return $next($request);
    7. }
    8. throw new UnauthorizedHttpException('jwt',"未登陆");
    9. }catch (TokenExpiredException $exception){
    10. try{
    11. $token = $this->auth->refresh();
    12. Auth::guard('api')->onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
    13. }catch (JWTException $exception){
    14. //刷新过期
    15. throw new UnauthorizedHttpException('jwt',"登录失效,请重新登录");
    16. }
    17. return $this->setAuthenticationHeader($next($request),$token);
    18. }catch (TokenBlacklistedException $exception){
    19. throw new UnauthorizedHttpException('jwt',"登录失效,请重新登录");
    20. }
    21. }