安裝使用jwt
1.下載laravel
composer create-project –prefer-dist laravel/laravel jwt 6.* (laravel版本號可寫可不寫)
2.安裝jwt擴充套件包
composer require tymon/jwt-auth:dev-develop –prefer-source
3.釋出資源(這條命令會在config中生成jwt.php配置檔案)
php artisan vendor:publish –provider=”Tymon\JWTAuth\Providers\LaravelServiceProvider”
4.生成jwt秘鑰
php artisan jwt:secret
5.註冊中介軟體
在app/Http/Kernel.php檔案中 $routeMiddleware中新增如下程式碼:
'auth.jwt' => \Tymon\JWTAuth\Http\Middleware\Authenticate::class,
在需要的路由加上 auth.jwt中介軟體就可以正常使用
6.在config/auth.php中
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',//token修改成jwt
'provider' => 'users',
'hash' => false,
],
],
注:這裡可以不修改
不修改使用方法如下:
use Tymon\JWTAuth\Facades\JWTAuth;
$input = $request->only('email', 'password');
JWTAuth::attempt($input)//加密
JWTAuth::invalidate($request->token);//刪除
JWTAuth::authenticate($request->token);//解密獲取資訊
修改之後使用方法如下(當然修改之後上面的方法還可以繼續使用):
auth('api')->attempt($input);
auth('api')->invalidate($request->token);
auth('api')->authenticate($request->token);
修改jwt預設使用者表
預設使用的是app\User.php(預設連結的是users表),模型內容如下:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use Notifiable;
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* 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 [];
}
}
修改成member表
1.建立member資料表和對應的模型檔案,模型檔案程式碼同上
2.修改config\auth中程式碼,如下:
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'member',//users修改成member
'hash' => false,
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
//新增member程式碼
'member' => [
'driver' => 'eloquent',
'model' => App\Models\Member::class,
],
],
本作品採用《CC 協議》,轉載必須註明作者和本文連結