laravel jwt验证

安装

composer安装 composer require tymon/jwt-auth
创建jwt签名 php artisan jwt:secret
修改config/auth.php 将api警卫修改为jwt

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'jwt',
        'provider' => 'users',
    ],
],

修改用户模型

<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail as MustVerifyEmailContract;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\MustVerifyEmail as MustVerifyEmailTrait;
use Auth;
use Spatie\Permission\Traits\HasRoles;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements MustVerifyEmailContract, JWTSubject
.
.
.
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }
}

使用

登录生成token

$credentials['username'] = $username;
$credentials['password'] = $password;

// 校验
if (!$access_token = \Auth::guard('api')->attempt($credentials)) {
// 登录失败
}

$token = [
    'access_token' => $access_token,
    'token_type' => 'Bearer',
    'expires_in' => Auth::guard('api')->factory()->getTTL() * 60
];

刷新token

$token = auth('api')->refresh();

删除token

auth('api')->logout();

路由中间件鉴权

Route::middleware('auth:api')->group(function () {
// 登录后可以访问的接口
});

当前用户数据

function nowUser(Request $request)
{
    return $request->user();
}

本文链接:

https://www.antixu.com/archives/414/
1 + 6 =
快来做第一个评论的人吧~