1. 程式人生 > >laravel使用JWT做認證登入

laravel使用JWT做認證登入

最近專案做API認證,最終技術選型決定使用JWT,專案框架使用的是laravel,laravel使用JWT有比較方便使用的開源包:jwt-auth。
使用composer安裝jwt-auth,laravel使用的框架版本為5.0,jwt-auth最新穩定版本為0.5.12。(最新版為1.0.*,需laravel5.4以上)
composer require tymon/jwt-auth 0.5.*
安裝完成後,需要在config/app.php中註冊相應的服務提供者:
'providers' => [
    'Tymon\JWTAuth\Providers\JWTAuthServiceProvider',
],
然後註冊需要用到的對應門面:
'aliases' => [
    'JWTAuth'   => 'Tymon\JWTAuth\Facades\JWTAuth',
    'JWTFactory' => 'Tymon\JWTAuth\Facades\JWTFactory',
],
然後釋出相應配置檔案:此命令會在 config 目錄下生成一個 jwt.php 配置檔案,你可以在此進行自定義配置。
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\JWTAuthServiceProvider"
最後生成金鑰:此命令會在你的 .env 檔案中新增一行 JWT_SECRET=secret
php artisan jwt:generate

生成TOKEN,生成TOKEN有多種方式:下面介紹兩種一、根據模型為基礎生成TOKEN:

根據模型生成TOKEN需在config/auth.php指定使用哪個模型。
    'model' => 'App\Models\Members',
在模型檔案Members.php中需新增
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;

class Members extends Model implements AuthenticatableContract
{
    use Authenticatable;
    ...
}
根據模型生成TOKEN
$member = \App\Models\Members::where('id',7)->select('id','username')->first();
$token = \JWTAuth::fromUser($member);
echo $token;exit;

二、自定義生成TOKEN:

$customClaims = ['sub' => [
    'id' => '7',
    'name' => 'kocor',
]];
$payload = \JWTFactory::make($customClaims);
$token = \JWTAuth::encode($payload);
echo $token;exit;

解密提取TOKEN資訊

提取TOKEN資訊
$user_info = JWTAuth::parseToken()->authenticate()
重新整理TOKEN
$newToken = JWTAuth::refresh($_REQUEST['token']);
使用例項
        //JWT提取會員資訊
        
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;


try {
    if (! $user_info = JWTAuth::parseToken()->authenticate()) {
        return Api::arr(config('statusCode.jwt_user_not_found'), trans('message.jwt_user_not_found').':404');
    }
    //在token有效期內允許重新整理
    $newToken = JWTAuth::refresh($_REQUEST['token']);
    return Api::json(config('statusCode.success'), trans('message.success'),$newToken);
} catch (TokenExpiredException $e) {
    try {
        //在重新整理有效期內
        $newToken = JWTAuth::refresh($_REQUEST['token']);
        return Api::json(config('statusCode.success'), trans('message.success'),$newToken);
    } catch (JWTException $e) {
        // 過期使用者
        return Api::json(config('statusCode.jwt_token_expired'), trans('message.jwt_token_expired').$e->getStatusCode());
    }
//無效的token
} catch (TokenInvalidException $e) {
    return Api::json(config('statusCode.jwt_token_invalid'), trans('message.jwt_token_invalid').$e->getStatusCode());
//token不存在
} catch (JWTException $e) {
    return Api::json(config('statusCode.jwt_token_absent'), trans('message.jwt_token_absent').$e->getStatusCode());
}    

by kocor