Laravel Passport集成API遇未认证错误:本地正常线上Ubuntu异常
Hey there! Let’s break down the most likely culprits and fixes since your setup works locally on Windows but fails on Ubuntu—server configuration differences are almost certainly the issue here.
Common Fixes to Try
1. Fix HTTPS/Proxy Header Configuration
Laravel Passport (and Laravel in production) expects secure requests by default, and if your Ubuntu server uses a reverse proxy (like Nginx or Apache) without properly forwarding protocol headers, token validation will fail.
- For Nginx: Add these lines to your site configuration inside the
locationblock handling PHP requests:proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Authorization $http_authorization; proxy_pass_header Authorization; - For Apache: Add this to your
.htaccessfile to ensure the Authorization header is passed through:RewriteEngine On RewriteCond %{HTTP:Authorization} ^(.*) RewriteRule .* - [e=HTTP_AUTHORIZATION:%1] - Then, update
config/app.phpto trust your proxy:'trust_proxies' => '*', // Or specify your server's IP for stricter security
2. Clear Configuration & Route Caches
Ubuntu servers often rely on cached configs, and even if you updated config/auth.php, old cached values might still be in use. Run these commands in your project root:
php artisan config:clear php artisan cache:clear php artisan route:clear php artisan passport:install --force
The --force flag ensures Passport regenerates its encryption keys, which is critical for production environments.
3. Verify Token Compatibility
Don’t test with tokens generated on your local Windows machine! Laravel uses your APP_KEY to encrypt Passport tokens, and if your local and Ubuntu APP_KEY values are different (which they should be for security), the server can’t decrypt local tokens. Always generate tokens directly on the Ubuntu server via your login API before testing protected routes.
4. Double-Check Auth Guard & Route Setup
Confirm your config/auth.php has the correct API guard driver:
'guards' => [ 'api' => [ 'driver' => 'passport', 'provider' => 'users', 'hash' => false, ], ],
And make sure your /get-details route is explicitly using the auth:api middleware:
Route::get('/get-details', [YourController::class, 'getDetails'])->middleware('auth:api');
5. Check Laravel Logs for Specific Errors
The best way to narrow down the issue is to look at Laravel’s error logs. On Ubuntu, run this command in your project root to tail the logs in real-time:
tail -f storage/logs/laravel.log
Then send a request to /get-details—the log will show exactly why authentication failed (e.g., missing Authorization header, invalid token, decryption error).
内容的提问来源于stack exchange,提问作者Jchauhan

