安裝使用jwt
1.下載laravel
composer create-project --prefer-dist laravel/laravel jwt 6.* (laravel版本號(hào)可寫可不寫)
2.安裝jwt擴(kuò)展包
composer require tymon/jwt-auth:dev-develop --prefer-source
3.發(fā)布資源(這條命令會(huì)在config中生成jwt.php配置文件)
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
4.生成jwt秘鑰
php artisan jwt:secret
5.注冊(cè)中間件
在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);//解密獲取信息
修改之后使用方法如下(當(dāng)然修改之后上面的方法還可以繼續(xù)使用):
auth('api')->attempt($input);
auth('api')->invalidate($request->token);
auth('api')->authenticate($request->token);
修改jwt默認(rèn)用戶表
默認(rèn)使用的是app\User.php(默認(rèn)鏈接的是users表),模型內(nèi)容如下:
<?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.創(chuàng)建member數(shù)據(jù)表和對(duì)應(yīng)的模型文件,模型文件代碼同上
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,
],
],