Seamless Authentication in Laravel Sanctum with Two Subdomains: A Comprehensive Guide
The Challenge: Bridging the Gap Between Subdomains
Modern web applications often leverage multiple subdomains to organize their functionality. This presents a challenge for authentication, particularly when using Laravel Sanctum for Single Page Applications (SPAs). Maintaining a consistent login experience across subdomains requires careful configuration and understanding of Sanctum's mechanics.
Scenario: Two Subdomains, One User Experience
Imagine a scenario where you have two subdomains: admin.example.com
for administrative tasks and app.example.com
for user-facing content. Both subdomains need to share the same user authentication system, allowing users to seamlessly access both domains without having to log in twice.
Original Code:
// Example Sanctum setup in your Laravel app
use Laravel\Sanctum\HasApiTokens;
// User model
class User extends Authenticatable
{
use HasApiTokens;
// ... other attributes and methods
}
// Route for the admin subdomain
Route::group(['domain' => 'admin.example.com'], function () {
// Protected admin routes here
});
// Route for the app subdomain
Route::group(['domain' => 'app.example.com'], function () {
// Protected app routes here
});
The Solution: Leveraging Sanctum's Power and Cookies
Laravel Sanctum provides a powerful solution for seamless authentication across subdomains. By leveraging cookies and a shared authentication mechanism, we can maintain a single user session across both admin.example.com
and app.example.com
.
Steps for Successful Authentication:
-
Configure Sanctum for Cross-Domain Cookies:
- In your
config/session.php
file, ensure thedomain
value matches the base domain:
'domain' => '.example.com',
This ensures the session cookie is set with a domain that both subdomains inherit.
- In your
-
Secure Your Routes:
- Apply the
middleware
group to both subdomain routes:
Route::group(['domain' => 'admin.example.com', 'middleware' => 'auth:sanctum'], function () { // Protected admin routes here }); Route::group(['domain' => 'app.example.com', 'middleware' => 'auth:sanctum'], function () { // Protected app routes here });
This enforces authentication using Sanctum's middleware for all routes within both subdomains.
- Apply the
-
Handle Authentication in Your SPA:
- Make sure your JavaScript code handles the authentication process for both subdomains. When a user logs in on one subdomain, the authentication token should be stored in the browser's cookies, allowing access to the other subdomain.
-
Protect Sensitive API Endpoints:
- Utilize the
auth:sanctum
middleware in your API routes to restrict access to authenticated users:
Route::group(['middleware' => 'auth:sanctum'], function () { // Protected API routes here });
- Utilize the
Example: A Secure Subdomain API
// App subdomain API routes
Route::group(['domain' => 'app.example.com', 'middleware' => 'auth:sanctum'], function () {
Route::get('/user', function (Request $request) {
return $request->user();
});
});
// Admin subdomain API routes
Route::group(['domain' => 'admin.example.com', 'middleware' => 'auth:sanctum'], function () {
Route::get('/admin-dashboard', function (Request $request) {
return 'Welcome to the Admin Dashboard!';
});
});
This code ensures that the user can access the /user
endpoint on the app.example.com
subdomain and the /admin-dashboard
endpoint on the admin.example.com
subdomain only after successful authentication.
Tips and Considerations
- Remember CORS: For SPA communication with your backend, configure your Laravel application to allow cross-origin requests (CORS) from both subdomains.
- JavaScript Client: Carefully manage the authentication state in your JavaScript client, ensuring consistent access across both subdomains. Use libraries like Axios or similar to send authenticated requests to your API endpoints.
- Security Best Practices: Always use HTTPS to protect user data transmitted over the internet, particularly when handling sensitive information like authentication tokens.
Conclusion
By applying these best practices, you can achieve seamless authentication for your SPA across multiple subdomains using Laravel Sanctum. This allows for a smooth user experience, regardless of which subdomain they access.
Remember to prioritize security measures and implement appropriate authentication checks in your JavaScript client to ensure a secure and efficient user experience.