Laravel Passport与Vue CLI对接时API认证401问题排查
Hey, let's figure out why your /api/user request is throwing a 401 even after successful login. The issue boils down to two key misconfigurations—one on the Laravel side, and one with your Vue/axios setup. Here's how to fix it step by step:
1. Fix Laravel Passport Setup
First, the laravel_token cookie you're expecting isn't being attached because you're missing a critical Passport middleware, and there might be a small tweak needed in your auth config.
Add the CreateFreshApiToken Middleware
Passport's CreateFreshApiToken middleware is responsible for generating and attaching the laravel_token cookie to authenticated responses. Open app/Http/Kernel.php and add it to your web middleware group:
protected $middlewareGroups = [ 'web' => [ // Keep your existing web middleware here... \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class, ], // ... ];
This middleware runs after the user is authenticated (via Auth::attempt in your login route) and automatically sets the cookie for you.
Verify API Guard Configuration
Make sure your API guard is set to use Passport. Open config/auth.php and check the api guard entry:
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ],
This tells Laravel to use Passport to authenticate API requests that carry the laravel_token cookie.
Adjust Your Login Route (Optional but Clean)
While your current login route works, you don't actually need to manually create an access token for the JavaScript consumption flow—Passport handles that via the cookie. You can simplify it (or keep it as-is, no harm done):
public function login(){ if(Auth::attempt(['email' => request('email'), 'password' => request('password')])){ $user = Auth::user(); // The CreateFreshApiToken middleware will handle the token cookie automatically return response()->json(['user' => $user], $this->successStatus); } else{ return response()->json(['error'=>'Unauthorised'], 401); } }
2. Configure Axios to Carry Credentials
Your Vue app isn't sending the laravel_token cookie with subsequent requests because axios isn't set to include credentials.
Global Axios Setup
In your Vue app's entry file (like main.js), add these lines to configure axios to send cookies with every request:
import axios from 'axios'; // Tell axios to include credentials (cookies) in requests axios.defaults.withCredentials = true; // Set your Laravel backend's base URL (adjust if your backend is on a different port/host) axios.defaults.baseURL = 'http://localhost:8000/';
Fix CORS with Vue Proxy (If Cross-Domain)
If your Vue app runs on localhost:8080 and Laravel on localhost:8000, you need a proxy to avoid CORS issues. Create or edit vue.config.js in your Vue project root:
module.exports = { devServer: { proxy: { '/api': { target: 'http://localhost:8000', changeOrigin: true, secure: false } } } }
This routes all /api requests from your Vue app to your Laravel backend, ensuring cookies are passed correctly.
Update Your Vue Action
You don't need to manually handle the token—axios will carry the laravel_token cookie automatically. Your action can stay mostly the same, but make sure you're catching errors for debugging:
login({commit, dispatch}, {email, password}){ axios.post('/api/login', { email, password }) .then(response => { console.log("Check login was successful", response.data); commit('setUser', response.data); // This request will now include the laravel_token cookie axios.get("/api/user") .then(response => console.log("Still logged in:", response)) .catch(err => console.error("User fetch error:", err)); }) .catch(err => console.error("Login failed:", err)); }
3. Verify the Cookie is Set
After logging in, open your browser's dev tools (Application tab -> Cookies) and check if laravel_token exists for your backend domain. If it does, your subsequent /api/user request should work without a 401.
内容的提问来源于stack exchange,提问作者Djave

