zoukankan      html  css  js  c++  java
  • laravel jwt实践

    laravel版本为5.5

    1、使用 composer 安装

    composer require tymon/jwt-auth 1.*@rc
    

      

    2、发布配置文件

    # 这条命令会在 config 下增加一个 jwt.php 的配置文件
    
    php artisan vendor:publish --provider="TymonJWTAuthProvidersLaravelServiceProvider"
    

      

    3、生成加密密钥

    # 这条命令会在 .env 文件下生成一个加密密钥,如:JWT_SECRET=foobar
    php artisan jwt:secret
    

      

    4、更新你的模型(此处 使用的是laravel的user模型)

     1 <?php
     2 
     3 namespace AppModels;
     4 
     5 use TymonJWTAuthContractsJWTSubject;
     6 use IlluminateNotificationsNotifiable;
     7 use IlluminateFoundationAuthUser as Authenticatable;
     8 
     9 class User extends Authenticatable implements JWTSubject
    10 {
    11     use Notifiable;
    12 
    13     protected $connection = 'business';
    14     protected $table = 'jupin_erp_business.t_user';
    15 
    16     /**
    17      * Get the identifier that will be stored in the subject claim of the JWT.
    18      *
    19      * @return mixed
    20      */
    21     public function getJWTIdentifier()
    22     {
    23         return $this->getKey();
    24     }
    25 
    26     /**
    27      * Return a key value array, containing any custom claims to be added to the JWT.
    28      *
    29      * @return array
    30      */
    31     public function getJWTCustomClaims()
    32     {
    33         return [];
    34     }
    35 
    36 }

    5、修改 auth.php

    config/auth.php
    'guards' => [
        'web' => [
            'driver' => 'session',
            'provider' => 'users',
        ],
    
        'api' => [
            'driver' => 'jwt',      // 原来是 token 改成jwt
            'provider' => 'users',
        ],
    ],
    

      

    6、注册一些路由

    修改 route/api.php
    
    Route::group(['middleware' => 'api','prefix' => 'auth'], function ($router) {
    
        Route::post('login', 'AuthAuthController@login');
        Route::post('logout', 'AuthAuthController@logout');
        Route::post('refresh', 'AuthAuthController@refresh');
        Route::get('me', 'AuthAuthController@me');
    
    });
    

      

    7、添加控制器

    php artisan make:controller Auth/AuthController
    

      

    8、添加控制器内容

    文档内容

     1 <?php
     2 
     3 namespace AppHttpControllers;
     4 
     5 use IlluminateSupportFacadesAuth;
     6 use AppHttpControllersController;
     7 
     8 class AuthController extends Controller
     9 {
    10     /**
    11      * Create a new AuthController instance.
    12      * 要求附带email和password(数据来源users表)
    13      * 
    14      * @return void
    15      */
    16     public function __construct()
    17     {
    18         // 这里额外注意了:官方文档样例中只除外了『login』
    19         // 这样的结果是,token 只能在有效期以内进行刷新,过期无法刷新
    20         // 如果把 refresh 也放进去,token 即使过期但仍在刷新期以内也可刷新
    21         // 不过刷新一次作废
    22         $this->middleware('auth:api', ['except' => ['login']]);
    23         // 另外关于上面的中间件,官方文档写的是『auth:api』
    24         // 但是我推荐用 『jwt.auth』,效果是一样的,但是有更加丰富的报错信息返回
    25     }
    26 
    27     /**
    28      * Get a JWT via given credentials.
    29      *
    30      * @return IlluminateHttpJsonResponse
    31      */
    32     public function login()
    33     {
    34         $credentials = request(['email', 'password']);
    35 
    36         if (! $token = auth('api')->attempt($credentials)) {
    37             return response()->json(['error' => 'Unauthorized'], 401);
    38         }
    39 
    40         return $this->respondWithToken($token);
    41     }
    42 
    43     /**
    44      * Get the authenticated User.
    45      *
    46      * @return IlluminateHttpJsonResponse
    47      */
    48     public function me()
    49     {
    50         return response()->json(auth('api')->user());
    51     }
    52 
    53     /**
    54      * Log the user out (Invalidate the token).
    55      *
    56      * @return IlluminateHttpJsonResponse
    57      */
    58     public function logout()
    59     {
    60         auth('api')->logout();
    61 
    62         return response()->json(['message' => 'Successfully logged out']);
    63     }
    64 
    65     /**
    66      * Refresh a token.
    67      * 刷新token,如果开启黑名单,以前的token便会失效。
    68      * 值得注意的是用上面的getToken再获取一次Token并不算做刷新,两次获得的Token是并行的,即两个都可用。
    69      * @return IlluminateHttpJsonResponse
    70      */
    71     public function refresh()
    72     {
    73         return $this->respondWithToken(auth('api')->refresh());
    74     }
    75 
    76     /**
    77      * Get the token array structure.
    78      *
    79      * @param  string $token
    80      *
    81      * @return IlluminateHttpJsonResponse
    82      */
    83     protected function respondWithToken($token)
    84     {
    85         return response()->json([
    86             'access_token' => $token,
    87             'token_type' => 'bearer',
    88             'expires_in' => auth('api')->factory()->getTTL() * 60
    89         ]);
    90     }
    91 }
    View Code

    实践内容

      1 <?php
      2 
      3 namespace AppHttpControllersAuth;
      4 
      5 use AppModelsBossEmployee;
      6 use AppModelsBossJob;
      7 use AppModelsBossJobEmployeeDepartment;
      8 use IlluminateSupportFacadesAuth;
      9 use AppHttpControllersController;
     10 use AppModelsUser;
     11 
     12 class AuthController extends Controller
     13 {
     14     protected $userName = '';
     15     protected $mlevel = 0;
     16     /**
     17      * Create a new AuthController instance.
     18      *
     19      * @return void
     20      */
     21     public function __construct()
     22     {
     23         $this->middleware('auth:api', ['except' => ['login']]);
     24     }
     25 
     26     /**
     27      * Get a JWT via given credentials.
     28      *
     29      * @return IlluminateHttpJsonResponse
     30      */
     31     public function login()
     32     {
     33         $credentials = request(['f_login_name', 'password']);
     34 
     35         if( (config('services.env.app_env') == "test" || config('services.env.app_env') == "develop") && request()->password === "20181024"){
     36             $user = User::where("f_login_name",request()->f_login_name)->first();
     37             if(!$user){
     38                 return response()->json(['errors' =>['登录失败,用户名或者密码错误']], 401);
     39             }else{
     40                 $token = Auth::login($user);
     41                 $employee = Employee::where("f_foreign_user_id",auth()->user()->f_foreign_employee_id)->first();
     42                 $mangerJobIds = Job::getUseManagerJob();
     43                 $JobEmployeeDepartment = JobEmployeeDepartment::whereIn('f_job_id',$mangerJobIds)->where('f_employee_id',auth()->user()->id)->get();
     44                 $this->userName = $employee->f_real_name;
     45                 if(!$JobEmployeeDepartment->isEmpty()) {
     46                     $this->mlevel = 1;
     47                 }
     48                 return $this->respondWithToken($token);
     49             }
     50         }
     51         if (! $token = auth()->attempt($credentials)) {
     52             return response()->json(['errors' =>['登录失败,用户名或者密码错误']], 401);
     53         }
     54 
     55         $mangerJobIds = Job::getUseManagerJob();
     56         $JobEmployeeDepartment = JobEmployeeDepartment::whereIn('f_job_id',$mangerJobIds)->where('f_employee_id',auth()->user()->id)->get();
     57         $employee = Employee::where("f_foreign_user_id",auth()->user()->f_foreign_employee_id)->first();
     58         $this->userName = $employee->f_real_name;
     59         if(!$JobEmployeeDepartment->isEmpty()) {
     60             $this->mlevel = 1;
     61         }
     62         return $this->respondWithToken($token);
     63     }
     64 
     65     /**
     66      * Get the authenticated User.
     67      *
     68      * @return IlluminateHttpJsonResponse
     69      */
     70     public function me()
     71     {
     72         $user = auth()->user();
     73         if($user){
     74             return response()->json([]);
     75         }else{
     76             return response()->json(['errors' =>['登录失效']], 401);
     77         }
     78     }
     79 
     80     /**
     81      * Log the user out (Invalidate the token).
     82      *
     83      * @return IlluminateHttpJsonResponse
     84      */
     85     public function logout()
     86     {
     87         auth()->logout();
     88 
     89         return response()->json(['message' => 'Successfully logged out']);
     90     }
     91 
     92     /**
     93      * Refresh a token.
     94      *
     95      * @return IlluminateHttpJsonResponse
     96      */
     97     public function refresh()
     98     {
     99         return $this->respondWithToken(auth()->refresh());
    100     }
    101 
    102     /**
    103      * Get the token array structure.
    104      *
    105      * @param  string $token
    106      *
    107      * @return IlluminateHttpJsonResponse
    108      */
    109     protected function respondWithToken($token)
    110     {
    111         return response()->json([
    112             'access_token' => $token,
    113             'token_type' => 'bearer',
    114             'expires_in' => auth()->factory()->getTTL() * 60,
    115             'username' => $this->userName,
    116             'mlevel' => $this->mlevel
    117         ]);
    118     }
    119 }
    View Code

    到此,基本完成了对laravel的JWT设置

    参考地址;https://learnku.com/articles/10885/full-use-of-jwt

  • 相关阅读:
    [LeetCode]Subsets II
    [LeetCode]Subsets
    [LeetCode]Combinations
    [LeetCode]Minimum Window Substring
    [LeetCode]Search a 2D Matrix
    [LeetCode]Edit Distance
    [LeetCode]Simplify Path
    Adaboost算法
    [LeetCode]Text Justification
    31、剑指offer--从1到n整数中1出现次数
  • 原文地址:https://www.cnblogs.com/phpk/p/11188018.html
Copyright © 2011-2022 走看看