一、安装JWT
composer require tymon/jwt-auth
二、config/app.php 注册服务提供者
'providers' => [Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
]
'aliases' => ['JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
]
三、发布生成配置文件
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
四、生成 JWT_SECRE(执行后会在.env 中自动生成:JWT_SECRET=**************)
php artisan jwt:secret
五、config/auth.php 中配置 guards
'guards' => ['web' => ['driver' => 'session','provider' => 'users',],'jf_api' => ['driver' => 'jwt','provider' => 'user',],],
'providers' => [//这里的users就是上面api中的provider的值users'user' => ['driver' => 'eloquent','model' => App\Models\Api\User::class,//注意这里的路径,我的api在Api目录下],],
六、新建 App\Models\Api\User 模型类,注意要继承 Authenticatable 并且 是JWTSubject 接口的实现
<?phpnamespace App\Models\Api;use App\Traits\SerializeDate;
use DateTimeInterface;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Tymon\JWTAuth\Contracts\JWTSubject;class User extends Authenticatable implements JWTSubject
{use HasFactory, Notifiable, SerializeDate;/*** 关联到模型的数据表** @var string*/protected $table = 'user';public $timestamps = false;//格式化输出时间protected function serializeDate(DateTimeInterface $date){return $date->format('Y-m-d H:i:s');}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 [];}}
<?phpnamespace App\Traits;use DateTimeInterface;trait SerializeDate
{/*** 为 array / JSON 序列化准备日期格式** @param \DateTimeInterface $date* @return string*/protected function serializeDate(DateTimeInterface $date){return $date->format('Y-m-d H:i:s');}
}
七、注册路由 JWT 认证扩展包附带了允许我们使用的中间件。在 app/Http/Kernel.php 中注册 auth.jwt 中间件
protected $routeMiddleware = [....'auth.jf.api' => \App\Http\Middleware\myMiddleware\AuthApi::class,
];
<?php
namespace App\Http\Middleware\myMiddleware;use Closure;class AuthApi{/*** 前台登陆鉴权* @param \Illuminate\Http\Request $request* @param \Closure $next* @return mixed*/public function handle($request, Closure $next){$admin = auth('api')->user();if (!$admin) {apiError('请先登录','',401);}return $next($request);}
}
八、创建api路由
<?php
use Illuminate\Support\Facades\Route;Route::prefix('user')->middleware(['auth.jf.api'])->group(function (){Route::get('/register', [\App\Http\Controllers\Api\UserController::class, 'register']);
});Route::prefix('index')->group(function (){Route::get('/index', [\App\Http\Controllers\Api\IndexController::class, 'index']);
});
九、控制器使用
php artisan make:controller Api\UserController
<?phpnamespace App\Http\Controllers\Api;use App\Http\Requests\UserRequests;
use App\Models\Api\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;//php artisan make:controller Api\UserController/*** 用户控制器* Class User* @package App\Http\Controllers\Api*/
class UserController extends Base
{public function register(Request $request, UserRequests $userRequests){$data=$request->all();$insertData['salt']=Str::random(4);$insertData['phone'] = $data['phone'];$insertData['password']=md5($data['password'].$data['salt']);$insertData['create_time'] = date("Y-m-d H:i:s",time());User::create($data);apiSuccess($data);}public function login(Request $request){$input = $request->only('account', 'password');//此处可以自己查数据库,判断是否用户名和密码正确$user = User::query()->where(['account' => $input['account']])->firstOrFail();//生成token$token = Auth::guard('jf_api')->fromUser($user);return response()->json(['success' => true,'token' => $token,'user' => $user,]);}public function logout(Request $request){Auth::guard('jf_api')->invalidate();return response()->json(['success' => true,'msg' => "退出成功"]);}public function refresh(Request $request){$newtoken=Auth::guard('jf_api')->refresh();return response()->json(['success' => true,'msg' => "token已刷新","token"=>$newtoken]);}public function user(Request $request){//两种方式都行$user = Auth::guard('jf_api')->user();//$user = JWTAuth::authenticate();return response()->json(['success' => true,'user' => $user,]);}
}