laravel9和之前的8有很大区别,先从常用的jwt入手,之前8我所使用的是tymon/jwt-auth这个包,在9里面发现这个包登录后返回1,没有成功的返回token。这个应该是可以修复的,但都是用三分包,所以就重新使用了一个。
一:安装JWT认证包
composer require php-open-source-saver/jwt-auth
二:发布配置文件
php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"
三:生成 JWT 密钥
php artisan jwt:secret
四:配置认证保护,修改config/auth.php
文件
'defaults' => [
'guard' => 'admin',
'passwords' => 'admins',
],
'guards' => [
'admin' => [
'driver' => 'jwt',
'provider' => 'admins',
],
],
'providers' => [
'admins' => [
'driver' => 'eloquent',
'model' => App\Models\Admin::class,
],
],
五:修改admin模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as AuthAdmin;
use Illuminate\Notifications\Notifiable;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
class Admin extends AuthAdmin implements JWTSubject
{
use HasFactory, Notifiable;
protected $fillable = [
'username', 'password',
];
protected $hidden = [
'password',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
六:创建一个检测登录的中间件:
php artisan make:middleware CheckAdmin
中间件的代码如下:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckAdmin
{
public function handle(Request $request, Closure $next)
{
// 获取管理员信息
$admin = auth()->user();
// 判断管理员没有登录
if (!$admin) {
// 返回401,提示登录
return response()->json(['code' => 401, 'msg' => '请先登录']);
}
return $next($request);
}
}
七:创建一个用于登录的控制器
php artisan make:controller Login
控制器文件代码如下
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class Login extends Controller
{
public function index(Request $request)
{
$credentials = $request->only('username', 'password');
$token = Auth::attempt($credentials);
if (!$token) {
return response()->json(['code' => 201, 'msg' => '登录失败']);
}
return response()->json(['code' => 200, 'msg' => '登录成功', 'data' => $token]);
}
public function test()
{
return 'ok';
}
}
在routes/admin.php路由中使用检测登录中间件:
<?php
use App\Http\Controllers\Login;
use App\Http\Middleware\CheckAdmin;
use Illuminate\Support\Facades\Route;
// 使用登录中间件,必须要登录
Route::middleware([CheckAdmin::class])->group(function () {
Route::get('/test', [Login::class, 'test']);
});