Integrate Laravel Login with WordPress
To allow automatic login to WordPress when a user logs into your Laravel application, you need to synchronize authentication between the two platforms. This requires a single sign-on (SSO) or shared session mechanism between Laravel and WordPress.
Here’s a step-by-step approach to achieve this:
1. Overview of the Process
When a user logs into your Laravel application:
- Generate a secure token (e.g., JWT or OAuth 2.0) during login in Laravel.
- Automatically pass this token to WordPress via a custom API or URL endpoint.
- Verify the token on the WordPress side.
- Log the user into WordPress programmatically.
2. Steps to Integrate Laravel Login with WordPress
Step 1: Install JWT Authentication in WordPress
You need WordPress to accept and validate tokens generated by Laravel. The easiest way is to use JWT Authentication.
- Install the JWT Authentication for WP REST API plugin on your WordPress site:
- Configure the plugin:
- Add the following lines to your
wp-config.php
:define('JWT_AUTH_SECRET_KEY', 'your-secret-key'); define('JWT_AUTH_CORS_ENABLE', true);
- Replace
'your-secret-key'
with a strong, unique secret key.
- Add the following lines to your
Step 2: Generate a JWT Token in Laravel
When a user logs into Laravel, generate a JWT token for that user. Install a package like Laravel Sanctum or Laravel Passport to manage token creation and validation.
Using Laravel Sanctum:
- Install Laravel Sanctum:
composer require laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate
- Add Sanctum middleware to your Laravel
api
routes inKernel.php
:'api' => [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ],
- Generate a token during login in Laravel:
use Illuminate\Support\Facades\Auth; use Laravel\Sanctum\PersonalAccessToken; public function login(Request $request) { $credentials = $request->only('email', 'password'); if (Auth::attempt($credentials)) { $user = Auth::user(); $token = $user->createToken('auth-token')->plainTextToken; return response()->json([ 'user' => $user, 'token' => $token ]); } return response()->json(['error' => 'Unauthorized'], 401); }
Step 3: Send the JWT to WordPress
After generating the JWT in Laravel, you need to send it to WordPress so the user can log in automatically.
- Redirect the user to a custom WordPress endpoint:
$wordpressLoginUrl = "https://your-wordpress-site.com/?laravel_token={$token}"; return redirect()->away($wordpressLoginUrl);
Step 4: Verify the Token in WordPress
Create a custom endpoint or use WordPress hooks to verify the Laravel token and log in the user.
- Add a custom function in your WordPress theme’s
functions.php
:function laravel_auto_login() { if (isset($_GET['laravel_token'])) { $token = sanitize_text_field($_GET['laravel_token']); // Verify the JWT using the same secret key $decoded = jwt_decode($token, JWT_AUTH_SECRET_KEY, ['HS256']); if ($decoded && isset($decoded->email)) { $user = get_user_by('email', $decoded->email); if ($user) { // Log in the user programmatically wp_set_current_user($user->ID); wp_set_auth_cookie($user->ID); wp_redirect(home_url()); exit; } } } } add_action('init', 'laravel_auto_login');
- Install the Firebase JWT library in WordPress for decoding JWT tokens:
composer require firebase/php-jwt
- Ensure the secret key (
JWT_AUTH_SECRET_KEY
) is the same in both Laravel and WordPress.
Step 5: Test the Integration
- Log into your Laravel application.
- The Laravel application will redirect the user to WordPress with the JWT token.
- WordPress verifies the token, logs in the user programmatically, and redirects them to the WordPress homepage.
3. Optional Enhancements
- Security: Ensure all token exchanges happen over HTTPS to prevent man-in-the-middle attacks.
- Token Expiration: Set short expiration times for tokens to avoid misuse.
- Error Handling: Handle edge cases like expired tokens or invalid user data gracefully.
- SSO Logout: Implement a logout mechanism to log out users from both Laravel and WordPress.
Conclusion
By using JWT tokens, you can bridge authentication between Laravel and WordPress. Laravel generates the token, and WordPress verifies it to log the user in programmatically. This provides a seamless login experience across both platforms.
Let me know if you need further clarification or implementation guidance! 🚀