You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React SPA+Laravel后端API认证方案咨询:弃用Cookie与Passport的替代方案

Practical Authentication Solutions for Your Laravel API (SPA + Mobile)

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 JWTSubject trait to your User model 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 localStorage or secure mobile storage) and include it in every API request via the Authorization header: 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 HasApiTokens trait to your User model.
  • 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 Authorization header as Bearer {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_token field to your users table 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.php and 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:38:02