To achieve seamless authentication across subdomains in Laravel, you can use Laravel's built-in support for session sharing across subdomains. Here's a step-by-step guide to help you set this up:
Step 1: Configure Session Domain
In your config/session.php file, set the domain option to your main domain. This will allow the session to be shared across all subdomains.
'domain' => '.mainsite.com',
The leading dot (.) is important as it tells the browser to share the session cookie with all subdomains.
Step 2: Use the Same Encryption Key
Ensure that both subdomains (site1.mainsite.com and site2.mainsite.com) are using the same APP_KEY in the .env file. This is crucial for consistent encryption and decryption of session data.
Step 3: Set Up CORS (Cross-Origin Resource Sharing)
If you are making requests between subdomains, ensure that CORS is properly configured. You can do this by setting up CORS in your app/Http/Middleware/VerifyCsrfToken.php file:
protected $except = [
'http://site1.mainsite.com/*',
'http://site2.mainsite.com/*',
];
Step 4: Handle CSRF Tokens
If you are still encountering CSRF token mismatches, ensure that your forms include the CSRF token. In Laravel Blade templates, you can include it using:
@csrf
For AJAX requests, ensure that the CSRF token is included in the request headers. You can set this up globally in JavaScript:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Step 5: Implement Auto-Login
Instead of posting encrypted data between sites, consider using a shared authentication system. If you are using Laravel's built-in authentication, the session sharing should handle this automatically. However, if you need to manually authenticate a user, you can use Laravel's Auth facade:
use Illuminate\Support\Facades\Auth;
// Assuming you have the user's email
$user = User::where('email', $email)->first();
if ($user) {
Auth::login($user);
}
Step 6: Test the Setup
After making these changes, test the login process by logging into one subdomain and navigating to the other. The session should persist, and you should remain logged in.
By following these steps, you should be able to switch between subdomains without needing to log in again. If you encounter any issues, double-check your session configuration and ensure that cookies are being set correctly.