React SPA+Laravel后端API认证方案咨询:弃用Cookie与Passport的替代方案
Absolutely, there are solid, straightforward options that fit your exact needs—no Cookie-dependent default auth or overkill Passport required. Let’s break down the best choices for your React SPA and mobile app setup:
1. JWT Authentication (JSON Web Tokens)
This is the go-to for stateless API authentication, perfect for both SPAs and mobile apps since it doesn’t rely on cookies. You’ll use the popular tymondesigns/jwt-auth package to handle token generation, validation, and refresh.
How to implement it:
- Install the package:
composer require tymon/jwt-auth - Publish the config and generate a secret key:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" php artisan jwt:secret - Add the
JWTSubjecttrait to yourUsermodel and implement the required methods to identify users via the token. - Create a login controller that validates user credentials, then returns a JWT token:
public function login(Request $request) { $credentials = $request->only('email', 'password'); if (!$token = auth()->attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } return $this->respondWithToken($token); } protected function respondWithToken($token) { return response()->json([ 'access_token' => $token, 'token_type' => 'bearer', 'expires_in' => auth()->factory()->getTTL() * 60 ]); } - On your React SPA and mobile app, store the token (in
localStorageor secure mobile storage) and include it in every API request via theAuthorizationheader:Bearer {your-token}.
Pros: Stateless, works seamlessly across SPA and mobile, widely adopted.
Cons: Requires handling token refresh logic when tokens expire, no built-in token revocation (you’ll need to implement this if needed).
2. Laravel Sanctum (Official, Lightweight)
Don’t sleep on Sanctum—it’s often thought of as just a SPA auth tool, but it’s perfect for mobile API tokens too, and it’s maintained by the Laravel team so you get first-party support.
How to implement it:
- Install Sanctum:
composer require laravel/sanctum - Publish the migration and run it to create the token storage tables:
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate - Add the
HasApiTokenstrait to yourUsermodel. - In your login controller, generate a plain-text token for the user (this is what you’ll send to the client):
public function login(Request $request) { $request->validate([ 'email' => 'required|email', 'password' => 'required', ]); $user = User::where('email', $request->email)->first(); if (! $user || ! Hash::check($request->password, $user->password)) { return response()->json(['error' => 'Invalid credentials'], 401); } $token = $user->createToken('mobile-or-spa-token')->plainTextToken; return response()->json(['token' => $token]); } - For your React SPA, you can either use Sanctum’s CSRF protection (if you want session-based auth for the SPA) or just use the Bearer token approach like mobile. For mobile, send the token in the
Authorizationheader asBearer {token}.
Pros: Official Laravel tool, built-in token revocation, supports both SPA and mobile with minimal setup, integrates with Laravel’s existing auth system.
Cons: Slightly less stateless than JWT (since tokens are stored in your database), but that’s a plus for security if you need to revoke tokens.
3. Custom API Token Authentication
If you want full control without any third-party packages, you can build a simple token system yourself.
How to implement it:
- Add an
api_tokenfield to youruserstable via migration:Schema::table('users', function (Blueprint $table) { $table->string('api_token', 80)->unique()->nullable()->default(null); }); - In your login controller, generate a random token (use Laravel’s
Str::random()), save it to the user, and return it:use Illuminate\Support\Str; public function login(Request $request) { $credentials = $request->only('email', 'password'); if (!auth()->attempt($credentials)) { return response()->json(['error' => 'Unauthorized'], 401); } $user = auth()->user(); $user->api_token = Str::random(60); $user->save(); return response()->json(['token' => $user->api_token]); } - Create a custom middleware to validate the token on incoming requests:
public function handle(Request $request, Closure $next) { $token = $request->header('Authorization') ? str_replace('Bearer ', '', $request->header('Authorization')) : null; if (!$token || !User::where('api_token', $token)->exists()) { return response()->json(['error' => 'Unauthorized'], 401); } return $next($request); } - Register the middleware in your
Kernel.phpand apply it to your API routes.
Pros: 100% customizable, no external dependencies.
Cons: You’ll need to handle edge cases like token expiration, secure storage, and revocation yourself—this is best for simple use cases where you don’t need advanced features.
Recommendation
For most cases, Laravel Sanctum is the best pick—it’s official, secure, and handles both your SPA and mobile needs with minimal hassle. If you need a completely stateless system, go with JWT. For simple, custom control, roll your own token system.
内容的提问来源于stack exchange,提问作者Ziyadin Shemsedinov

