创建项目、配置请参考文档。
Laravel 11 默认没有创建 routes/api.php 文件,
初始化 API 配置
创建了 routes/api.php 文件,并在 bootstrap/app.php 文件中自动配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 <?php use Illuminate \Auth \AuthenticationException ;use Illuminate \Foundation \Application ;use Illuminate \Foundation \Configuration \Exceptions ;use Illuminate \Foundation \Configuration \Middleware ;use Illuminate \Http \Request ;use Symfony \Component \HttpFoundation \Response ;use Symfony \Component \HttpKernel \Exception \NotFoundHttpException ;return Application ::configure (basePath : dirname (__DIR__ )) ->withRouting ( web : __DIR__ . '/../routes/web.php' , api : __DIR__ . '/../routes/api.php' , // 自动注册 commands : __DIR__ . '/../routes/console.php' , health : '/up' , ) ->withMiddleware (function (Middleware $middleware ) { }) ->withExceptions (function (Exceptions $exceptions ) { })->create ();
进一步配置,在遇到未登录的情况返回错误提示而不是跳转到登录页面:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 return Application ::configure (basePath : dirname (__DIR__ )) ->withRouting ( web : __DIR__ . '/../routes/web.php' , api : __DIR__ . '/../routes/api.php' , commands : __DIR__ . '/../routes/console.php' , health : '/up' , ) ->withMiddleware (function (Middleware $middleware ) { }) ->withExceptions (function (Exceptions $exceptions ) { $exceptions ->render (function (AuthenticationException $e , Request $request ) { if ($request ->is ('api/*' )) { return response ()->json ([ 'message' => $e ->getMessage (), ], Response ::HTTP_UNAUTHORIZED ); } }); })->create ();
安装设置 JWT 包 1 composer require php-open-source-saver/jwt-auth
发布配置文件
1 php artisan vendor:publish --provider="PHPOpenSourceSaver\JWTAuth\Providers\LaravelServiceProvider"
生成 secret key,保存在 .env 文件中:
在 config/auth.php 文件中修改 auth guard 配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 'defaults' => [ 'guard' => 'api' , 'passwords' => 'users' , ], 'guards' => [ 'web' => [ 'driver' => 'session' , 'provider' => 'users' , ], 'api' => [ 'driver' => 'jwt' , 'provider' => 'users' , ], ],
完善用户(User)模型 实现 JWTSubject 接口:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 <?php namespace App \Models ; use Illuminate \Database \Eloquent \Factories \HasFactory ;use Illuminate \Foundation \Auth \User as Authenticatable ;use Illuminate \Notifications \Notifiable ;use PHPOpenSourceSaver \JWTAuth \Contracts \JWTSubject ; class User extends Authenticatable implements JWTSubject { use HasFactory , Notifiable ; protected $fillable = [ 'name' , 'email' , 'password' , ]; protected $hidden = [ 'password' , 'remember_token' , ]; protected function casts ( ): array { return [ 'email_verified_at' => 'datetime' , 'password' => 'hashed' , ]; } public function getJWTIdentifier ( ) { return $this ->getKey (); } public function getJWTCustomClaims ( ) { return []; } }
创建用户相关的 API 1 php artisan make:controller AuthController
完善 app/Http/Controllers/AuthController.php:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 <?php namespace App \Http \Controllers ; use App \Http \Controllers \Controller ;use App \Models \User ;use Validator ; class AuthController extends Controller { public function register ( ) { $validator = Validator ::make (request ()->all (), [ 'name' => 'required' , 'email' => 'required|email|unique:users' , 'password' => 'required|confirmed|min:8' , ]); if ($validator ->fails ()){ return response ()->json ($validator ->errors ()->toJson (), 400 ); } $user = new User ; $user ->name = request ()->name; $user ->email = request ()->email; $user ->password = bcrypt (request ()->password); $user ->save (); return response ()->json ($user , 201 ); } public function login ( ) { $credentials = request (['email' , 'password' ]); if (! $token = auth ()->attempt ($credentials )) { return response ()->json (['error' => 'Unauthorized' ], 401 ); } return $this ->respondWithToken ($token ); } public function me ( ) { return response ()->json (auth ()->user ()); } public function logout ( ) { auth ()->logout (); return response ()->json (['message' => 'Successfully logged out' ]); } public function refresh ( ) { return $this ->respondWithToken (auth ()->refresh ()); } protected function respondWithToken ($token ) { return response ()->json ([ 'access_token' => $token , 'token_type' => 'bearer' , 'expires_in' => auth ()->factory ()->getTTL () * 60 ]); } }
注册路由 在 routes/api.php 文件中添加:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 <?php use Illuminate \Support \Facades \Route ;use App \Http \Controllers \AuthController ; Route ::group ([ 'middleware' => 'api' , 'prefix' => 'auth' ], function ($router ) { Route ::post ('/register' , [AuthController ::class , 'register' ])->name ('register' ); Route ::post ('/login' , [AuthController ::class , 'login' ])->name ('login' ); Route ::post ('/logout' , [AuthController ::class , 'logout' ])->middleware ('auth:api' )->name ('logout' ); Route ::post ('/refresh' , [AuthController ::class , 'refresh' ])->middleware ('auth:api' )->name ('refresh' ); Route ::post ('/me' , [AuthController ::class , 'me' ])->middleware ('auth:api' )->name ('me' ); });
参考:https://www.binaryboxtuts.com/php-tutorials/laravel-11-json-web-tokenjwt-authentication/