Laravel鉴权中间件JWT使用教程
2020-08-11 本文已影响0人
刀鱼要到岛上掉
一次JWT使用笔记
1.使用 composer 安装
composer require tymon/jwt-auth 1.*@rc
2.发布配置文件
# 这条命令会在 config 下增加一个 jwt.php 的配置文件
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
3.更新你的模型
<?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 [];
}
}
4. 修改 auth.php
'api' => [
'driver' => 'jwt',
"provider" => 'api',
],
...
'api' => [
'driver' => 'eloquent',
'model' => App\Models\Users\Api::class,//这里使用模型,也可以使用数据表 driver设为database table=>'表名'
],
5.控制器
<?php
use Tymon\JWTAuth\Facades\JWTAuth;
class AuthController extends ApiController
{
public function __construct(){
// 这里额外注意了:官方文档样例中只除外了『login』
// 这样的结果是,token 只能在有效期以内进行刷新,过期无法刷新
// 如果把 refresh 也放进去,token 即使过期但仍在刷新期以内也可刷新
// 不过刷新一次作废
$this->middleware('jwt.auth', ['except' => ['Login', 'Refresh']]);
// 另外关于上面的中间件,官方文档写的是『auth:api』
// 但是我推荐用 『jwt.auth』,效果是一样的,但是有更加丰富的报错信息返回
}
public function postAdmin(Request $request)
{
$user= $request->input('appid', '');
$pwd= $request->input('secret', '');
$credentials = ['appid'=>$user, 'password'=>$pwd];
if (! $token = auth('apps')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return $this->respondWithToken($token);
}
public function postAdminRefresh()
{
try {
return $this->output(200, '获取成功', [
'access_token' => auth('apps')->refresh(),
'token_type' => 'bearer',
'expires_in' => JWTAuth::factory()->getTTL() * 60
]);
} catch (\Exception $e) {
Log::info('postRefresh:'.$e->getMessage().' line:'.$e->getLine());
return $this->output(400, "获取失败");
}
}
/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function postLogout()
{
auth('api')->invalidate();
return $this->output(200, '退出成功');
}
/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return $this->output(200, '获取成功', [
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => JWTAuth::factory()->getTTL() * 60
]);
}
}
6.写路由
Route::group(['namespace' => 'Api',"middleware" => 'jwt.auth'], function () {
//下面写你的路由
}