To implement automatic login for client's users in a multi-tenant application, you can use a Single Sign-On (SSO) approach. Laravel Passport, which is an OAuth2 server implementation, can be used for this purpose. Here's a high-level overview of how you can achieve this:
-
Set up Laravel Passport: Install and configure Laravel Passport in your application. This will be used to issue access tokens to your client's users.
-
Create an OAuth Client: For each tenant (client), create an OAuth client in your application. This client will be used to request tokens on behalf of their users.
-
Implement the SSO Endpoint: Create an endpoint on your application that the client's application can redirect to for authentication. This endpoint will handle the OAuth authorization flow.
-
Handle the Redirect from the Client's Application: When a user visits
subdomain.customer-app.com, the client's application should check if the user is logged in. If not, it should redirect the user to the SSO endpoint on your application with the appropriate OAuth parameters. -
Authenticate and Redirect Back: Your application will authenticate the user (prompting for login if necessary) and then redirect back to the client's application with an authorization code.
-
Exchange the Authorization Code for an Access Token: The client's application will then exchange the authorization code for an access token by making a request to your application's token endpoint.
-
Automatic Login: Once the client's application has the access token, it can use it to automatically log in the user by creating a session or a cookie.
Here's a simplified code example of how you might set up the SSO endpoint in your Laravel application:
// routes/web.php
use Illuminate\Http\Request;
use Laravel\Passport\Http\Controllers\AuthorizationController;
Route::get('/sso', [AuthorizationController::class, 'authorize']);
And the client's application might handle the redirect like this:
// Client's application (pseudo-code)
if (!userIsLoggedIn()) {
redirectToSSOEndpoint();
}
function redirectToSSOEndpoint() {
// The client_id and redirect_uri will be specific to the client's OAuth client
// that you created in your application.
$query = http_build_query([
'client_id' => 'client-id',
'redirect_uri' => 'https://subdomain.customer-app.com/callback',
'response_type' => 'code',
'scope' => '',
]);
header('Location: https://subdomain.my-app.com/sso?' . $query);
exit;
}
Remember to handle the callback on the client's application to exchange the authorization code for an access token and create a session for the user.
Please note that this is a simplified example and you'll need to handle various edge cases and security considerations, such as validating state parameters, handling errors, and ensuring secure token storage. Additionally, you'll need to customize the user authentication flow based on your specific requirements and user model.