文档:https://jwt-auth.readthedocs.io/en/develop/laravel-installation/
1.composer下载加密解密
composer require firebase/php-jwt
2.在下载的文件JWT.php中decode中加jti校验
if(isset($payload->jti)){
if(!isset($allowed_algs['jti'])||$payload->jti!=$allowed_algs['jti']){
throw new ExpiredException('Jti check defeat');
}
}
3.下载auth认证
composer require tymon/jwt-auth:1.0.0-rc.4.1
4.生成jwt配置文件
php artisan vendor:publish --provider=“Tymon\JWTAuth\Providers\LaravelServiceProvider”
5.生成jwt私钥
php artisan jwt:secret(.env中自动生成)
6.conf/app.php加入
'providers' => [
...
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]
7.app/User.php继承JwtSubject
<?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;
// 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 [];
}
}
8.config/auth.php修改
'api' => [
'driver' => 'jwt',
'provider' => 'users',
'hash' => false,
],
9.控制器方法
<?php
namespace App\Http\Controllers\Api\v1;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AuthController extends Controller
{
//
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
if (! $token = auth('api')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
echo $token;die;
return $this->respondWithToken($token);
}
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function me()
{
return response()->json(auth('api')->user());
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth('api')->logout();
return response()->json(['message' => 'Successfully logged out']);
}
/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth('api')->refresh());
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60
]);
}
}
10。api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::group(
['prefix'=>"v1","namespace"=>"Api\\v1"],function (){
//\Illuminate\Support\Facades\Route::resource("user","UserController");
\Illuminate\Support\Facades\Route::post("login","AuthController@login");
\Illuminate\Support\Facades\Route::post("logout","AuthController@logout");
\Illuminate\Support\Facades\Route::post("refresh","AuthController@refresh");
}
);
注意:宽限时间是为了解决并发请求的问题,假如宽限时间为 0s ,那么在新旧 token 交接的时候,并发请求就会出错,所以需要设定一个宽限时间,在宽限时间内,旧 token 仍然能够正常使用。
// 宽限时间需要开启黑名单(默认是开启的),黑名单保证过期token不可再用,最好打开
'blacklist_enabled' => env('JWT_BLACKLIST_ENABLED', true)
// 设定宽限时间,单位:秒
'blacklist_grace_period' => env('JWT_BLACKLIST_GRACE_PERIOD', 60)