Wednesday, June 18, 2025

Implementation of seamless authentication between two Laravel apps

 

When a user logs in to one application, they should also be authenticated in other application without logging in again.

1. Use a Common Authentication System

Ensure both Laravel apps share the same user database (either directly or via API).


2. Use tymon/jwt-auth in both apps

Install JWT package in both:

composer require tymon/jwt-auth
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider" php artisan jwt:secret

Do this in both apps. Say App A and App B


3. Generate Token in App A on Login

In App A, modify the login logic to generate a JWT token:

use Tymon\JWTAuth\Facades\JWTAuth;
public function login(Request $request) { $credentials = $request->only('email', 'password'); if (!$token = JWTAuth::attempt($credentials)) { return response()->json(['error' => 'Invalid credentials'], 401); } // Send token to front-end return response()->json(['token' => $token]); }

4. Share JWT Token with App B

When user logs in:

  1. Save token in a secure cookie:


return response()->json(['success' => true])->cookie( 'jwt_token', $token, 60, '/', '.seellab.com', true, true, false, 'Strict' );

✅ This cookie is available to all subdomains, like  App A and App B

  1. Alternatively, you can redirect to App B with token in query:

a
https://appbUrl/auth/jwt-login?token=xyz123

5. Accept and Authenticate in App B

In AppB, create a route like:

Route::get('/auth/jwt-login', function (Request $request) { $token = $request->get('token') ?? $request->cookie('jwt_token'); try { $user = JWTAuth::setToken($token)->authenticate(); Auth::login($user); return redirect('/dashboard'); // or wherever } catch (\Exception $e) { return redirect('/login')->withErrors('Token Invalid'); } });

You can auto-trigger this on page load, or have a middleware that checks and redirects accordingly.


6. Keep It Secure

  • Use HTTPS.

  • Mark cookie as Secure, HttpOnly, and SameSite=Strict if possible.

  • Tokens should expire, and refresh tokens can be used optionally.

  • If hosting under different domains (not subdomains), cookies won't be shareable — you'll need to redirect with the token.


Optional: Middleware in App B

Create a middleware to auto-login using the JWT cookie if user not logged in:

public function handle($request, Closure $next)
{ if (!Auth::check() && $request->cookie('jwt_token')) { try { $user = JWTAuth::setToken($request->cookie('jwt_token'))->authenticate(); Auth::login($user); } catch (\Exception $e) { // token expired or invalid } } return $next($request); }

Summary

FeatureImplementation
Token Generation            On login in App A
Token SharingSecure Cookie or URL param
Token ReadingApp B reads token from cookie/URL
Login SessionAuth::login($user) in App B
SecurityHTTPS, HttpOnly, SameSite, Token Expiry

No comments: