1. 安装
composer require php-open-source-saver/jwt-auth
2. 发布配置文件
php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"
3. 生成密钥
php artisan jwt:secret
4. 更新模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
// 'email_verified_at' => 'datetime',
];
/**
* 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 [];
}
}
5. 修改config/auth.php
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
//新增api配置
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
6 创建控制器
<?php
namespace App\Http\Controllers;
class LoginController extends Controller
{
public function login()
{
$credentials = request(['name','password']);
if (!$token = auth('api')->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 8401);
}
return $this->respondWithToken($token);
}
/**
* 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());
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
'expires_in' => auth('api')->factory()->getTTL() * 600
]);
}
}
7. 创建路由
Route::post('login', [LoginController::class,'login']);
//需要登录的路由 中间件可以用jwt.auth,错误提示比较友好,官方的auth:api
Route::group(['middleware'=>'auth:api'],function ($route){
//退出
Route::post('logout',[LoginController::class,'logout']);
});