Laravel Passport OAuth路由始终返回401未授权问题求助
Hey there, let's break down why you're hitting that 401 Unauthorized on all oauth/* routes while trying to run both JWT and OAuth side by side. Based on your config, here are the key issues and fixes:
1. Your web Guard is Using JWT (Breaks Passport's Core Flow)
Passport's authorization routes (like oauth/authorize) depend on the web guard with session authentication to handle user login and the OAuth consent workflow. But you’ve set your web guard to use the jwt driver, which doesn’t support sessions. This means when you hit an OAuth route, the app tries to authenticate you via JWT (no token = 401) instead of showing the login/consent page.
Fix:
Split your guards to keep web for Passport's session-based flows, while retaining api for your JWT API:
'guards' => [ 'web' => [ 'driver' => 'session', // Revert to session for Passport's web UI flows 'provider' => 'myappprovider', ], 'api' => [ 'driver' => 'jwt', 'provider' => 'myappprovider', ], 'oauth-api' => [ 'driver' => 'passport', 'provider' => 'myappprovider' ] ],
2. Your web Middleware Group is Missing Session Support
Passport's web routes need session middleware to track user state during authorization. Your current web group only includes your custom Language middleware—no session-related middleware, so the app can’t maintain a user session for the OAuth flow.
Fix:
Add back Laravel’s default session middleware to the web group:
'middlewareGroups' => [ 'web' => [ \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, 'language' => \App\Http\Middleware\Language::class, // Keep your custom middleware ], 'api' => [ 'throttle:60,1', 'auth:api' ], 'oauth-api' => [ 'auth:oauth-api' ] ],
3. Explicitly Bind Passport Routes to the web Middleware (Optional)
To ensure Passport uses the correct middleware group, specify it when registering routes in AuthServiceProvider:
Passport::routes(null, [ 'middleware' => ['web'] // Guarantee Passport routes use session-enabled web middleware ]);
4. Verify Your Authenticate Middleware Behavior
Your current Authenticate middleware checks if the user is a guest on the specified guard. For the web guard (now using sessions), this will redirect to your login page instead of returning a JSON 401—exactly what you need for the OAuth authorization flow. Make sure your login route uses the web guard so users can authenticate via session to approve OAuth requests.
Quick Post-Fix Test:
- Clear your config cache:
php artisan config:clear - Log in via your web login route (using the session guard)
- Try accessing
oauth/authorizeagain—you should see the OAuth consent page instead of a 401 - Your existing JWT API routes will continue working as expected since they use the
apiguard with the JWT driver
That should resolve the 401 issue while keeping your JWT API intact!
内容的提问来源于stack exchange,提问作者ybert

