1. 程式人生 > >laravel5.5-----jwt生成與驗證token

laravel5.5-----jwt生成與驗證token

一、生成token

準備工作:

1、在控制器裡引入 Tymon\JWTAuth\Facades\JWTAuth;

2、修改指定模型,我的是預設模型APP\User.php;

<?php

namespace App;

use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    protected  $table = 'test';

    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }
}
預設操作的表為users,指定自己的使用者表,我的是test表
 protected  $table = 'test';

方法:

1、使用JWTAuth::attempt():

$param = array(
       'email'=>123456789
       'password'=>''
);
return JWTAuth::attempt($param);

方法會根據你指定定義的模型裡面的定義的表進行查詢,欄位需要對應,密碼需要根據要求加密,不然不會生成token

2、使用JWTAuth::fromUser();

$user = User::first();
return JWTAuth::fromUser($user);

需要使用模型層來獲取使用者例項,使用DB查詢不符合方法需要的資料

二、驗證token

1、驗證

在中介軟體裡驗證對token進行驗證,在App\Http\Kernel.php裡面的路由中介軟體裡新增

 protected $routeMiddleware = [
         ........
        'jwt.api.auth' => \App\Http\Middleware\CheckToken::class,
]

在App\Http\Middleware裡面新增中介軟體檔案,我的檔名字是checktoken.php

<?php  
  
namespace App\Http\Middleware;  
  
use Closure;  
use JWTAuth;  
use Tymon\JWTAuth\Exceptions\JWTException;  
use Tymon\JWTAuth\Exceptions\TokenExpiredException;  
use Tymon\JWTAuth\Exceptions\TokenInvalidException;  
  
class CheckToken  
{  
    /**  
     * @param  \Illuminate\Http\Request  $request  
     * @param  \Closure  $next  
     * @return mixed  
     */  
public function handle($request, Closure $next)  
{  
    try {  
  
        if (! $user = JWTAuth::parseToken()->authenticate()) {  //獲取到使用者資料,並賦值給$user
            return response()->json([  
                'errcode' => 1004,  
                'errmsg' => 'user not found' 
 
            ], 404);  
        } 
        //如果想向控制器裡傳入使用者資訊,將資料新增到$request裡面
        $request->attributes->add($userInfo);//新增引數
        return $next($request);  
  
    } catch (TokenExpiredException $e) {  
  
        return response()->json([  
            'errcode' => 1003,  
            'errmsg' => 'token 過期' , //token已過期
        ]);  
  
    } catch (TokenInvalidException $e) {  
  
        return response()->json([  
            'errcode' => 1002,  
            'errmsg' => 'token 無效',  //token無效
        ]);  
  
    } catch (JWTException $e) {  
  
        return response()->json([ 
            'errcode' => 1001,  
            'errmsg' => '缺少token' , //token為空
        ]);  
  
    }  

    
}  
}  

其中JWTAuth::parseToken()->authenticate()用來獲取使用者資訊,傳過來的token如果只包含使用者id,不可以修改欄位名字,不然在使用者表裡不能查詢到相應的使用者資訊,返回值是完整的使用者資訊

2、在控制器裡獲取使用者資訊(laravel中介軟體部分知識)

public function userInfo(Request $request){
    //只取使用者id
     $id = $request->get('id');
}

token失效使用JWTAuth::invalidate();

jwt簡介與安裝上一章