同域外部脚本如何通过Ajax简便验证Laravel用户授权?
Hey there, great question! Using cookies for same-domain Ajax authentication is actually Laravel's default, far simpler approach—no need to manage api tokens at all for this scenario. Let me break down how it works and how to set it up smoothly.
Why This Works
Laravel's default session-based authentication relies entirely on cookies to track logged-in users. Since your Ajax request is same-domain, modern browsers will automatically send the session cookie along with the request (as long as you configure things right). That means Auth::check() will just work out of the box, no extra token handling required.
Step-by-Step Setup
1. Configure Your Ajax Requests Correctly
First, make sure your Ajax calls are set to include credentials (cookies) and carry the Laravel CSRF token (critical for same-domain requests to avoid 419 errors).
For jQuery:
First, set up a global Ajax config to include the CSRF token (pulled from the meta tag Laravel generates by default):$.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }, xhrFields: { withCredentials: true } });Then your auth check request looks like this:
$.ajax({ url: '/check-auth', method: 'GET', success: function(response) { if (response.authenticated) { console.log('User is logged in!'); // Handle authenticated state } else { console.log('User is not logged in.'); // Handle guest state } } });For Native Fetch:
Include credentials and the CSRF token in the request headers:const csrfToken = document.querySelector('meta[name="csrf-token"]').content; fetch('/check-auth', { method: 'GET', credentials: 'include', headers: { 'X-CSRF-TOKEN': csrfToken } }) .then(response => response.json()) .then(data => { if (data.authenticated) { // Do something for logged-in users } });
2. Set Up the Laravel Route & Logic
Use a web route (not an API route) because web routes automatically include the session middleware that powers Laravel's cookie-based auth.
Add this to routes/web.php:
Route::get('/check-auth', function () { return response()->json([ 'authenticated' => Auth::check() ]); });
Or if you prefer using a controller method:
// In your controller (e.g., UserController.php) public function checkAuthStatus() { return response()->json([ 'authenticated' => Auth::check() ]); } // Then in routes/web.php Route::get('/check-auth', [UserController::class, 'checkAuthStatus']);
3. Verify Session Configuration
Double-check your config/session.php to make sure cookies are set up for your domain:
domain: Set this to your app's domain (e.g.,'example.com'or'.example.com'to support subdomains)secure: Set totrueif your app uses HTTPS, otherwisefalsesame_site: Recommended to set to'lax'(strikes a good balance between security and usability)
Key Notes
- Don't use API routes for this: API routes are configured to use token-based auth by default and don't load the session middleware—so
Auth::check()will always return false there. - CSRF protection is mandatory: Laravel blocks unauthenticated same-domain requests without a valid CSRF token, so don't skip adding that header.
- This is way simpler than api tokens: No need to generate, store, or pass tokens around. The browser handles cookie management automatically, and you reuse Laravel's built-in auth system.
内容的提问来源于stack exchange,提问作者Alex

