2021-08-13 laravel jwt
2021-08-28 本文已影响0人
浩克啊12138
- 安装必要的第三方包
$ composer require overtrue/wechat:~5.0 -vvv
- 修改
config/app.php
中的providers
和aliases
'providers' => [
...
/*
* Package Service Providers...
*/
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
...
],
'aliases' => [
...
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
],
3.修改config/auth.php
中的 providers
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\Member\Members::class,
// 这个根据项目设置, 我这里的用户表用的是member所以这里的模型需要换成对应的Members类
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
- 发布配置, 发布后会自动生成一个配置文件
config/jwt.php
$ php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
- 模型设置, 我这边用的是Member, 使用其他模型也可以
use Illuminate\Auth\Authenticatable as AuthenticableTrait;
use Illuminate\Contracts\Auth\Authenticatable;
class Member extends Model implements Authenticatable
{
use AuthenticableTrait;
}
- 生成jwt的加密key
$ php artisan jwt:secret
- 登录控制器
...
// 自定义一个以payload变量
$customClaims = ['sub' => ['member' => $member->toArray()]];
$payload = JWTFactory::customClaims($customClaims)->make();
if (!$token = JWTAuth::encode($payload)->get()) {
throw new \Exception('Unauthorized');
}
// $ttl = $request->out_time ?? config('jwt.ttl'); # 设置token 过期时间
// if (!$token = Auth::guard('api')->setTTL($ttl)->tokenById($user->id)) {
// return ['code' => 500, 'massage' => 'token 过期'];
// }
// return apiJson($this->respondWithToken($token));
return ['token' => $token, 'member' => $member];
- 中间件校验
public function handle($request, Closure $next)
{
try {
$token = JWTAuth::getToken();
if (empty($token)) {
return response()->json(['status_code' => 4001, 'message' => '未登录']);
}
$sub = JWTAuth::setToken($token)->getPayload()->get('sub');
if (empty($sub)) {
return response()->json(['status_code' => 4002, 'message' => '用户异常']);
}
//如果想向控制器里传入用户信息,将数据添加到$request里面
$request->attributes->add(['member' => json_encode($sub->member)]); //添加参数
//其他地方获取用户值
// var_dump($request->attributes->get('member'));exit();
return $next($request);
} catch (TokenExpiredException $e) {
try {
$token = JWTAuth::refresh();
if ($token) {
return response()->json(['status_code' => 4003, 'message' => '新token', 'token' => $token]);
}
} catch (JWTException $e) {
return response()->json(['status_code' => 4004, 'message' => 'token无效', 'token' => '']);
}
}
// catch (\Exception $e) {
// return response()->json(['status_code' => 500, 'message' => 'token无效']);
// }
}