Implementing OAuth2 Single Sign-On (SSO) in Laravel with Passport
This guide walks through integrating OAuth2 Single Sign-On into a Laravel application using Laravel Passport, covering prerequisites, installation steps, configuration of the authentication server and client, testing procedures, and common troubleshooting tips to enhance security and user experience.
Single Sign-On (SSO) provides great convenience by allowing users to authenticate to multiple applications with a single set of credentials, managed by a central identity provider, enabling seamless switching and improved efficiency.
OAuth2, a widely adopted authorization framework, grants limited access to user accounts on HTTP services, protecting data security and privacy. Combined with SSO, it forms a powerful solution for managing cross‑system user access.
This article explores how to implement an OAuth2 SSO solution in a Laravel application, enhancing system security, ensuring data confidentiality, and simplifying the login process to improve usability and appeal.
Prerequisites
Before starting, make sure the following conditions are met:
Laravel environment: Laravel 8.x or higher installed; Laravel 8 introduces many updates that simplify handling packages such as Laravel Passport.
Composer installed: Composer is required for managing Laravel and third‑party packages.
Database configuration: A supported relational database (MySQL, PostgreSQL, or SQLite) is set up and running.
Knowledge base: Familiarity with Laravel architecture (routes, controllers, views), MVC concepts, and a basic understanding of OAuth2 authentication mechanisms.
Step‑by‑Step Deployment
1. Install Laravel Passport:
Run the following Composer command to add Passport:
composer require laravel/passport2. Migrate the database:
Passport provides migrations that automatically create the necessary tables.
php artisan migrate3. Install Passport:
This step generates encryption keys and configures the OAuth2 server.
php artisan passport:install4. Configure Passport in config/auth.php :
Set the API guard driver to passport as shown below:
'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],Configure Laravel as an OAuth2 Client
1. Environment configuration:
Update the .env file with the OAuth2 server details:
OAUTH_CLIENT_ID=your-client-id
OAUTH_CLIENT_SECRET=your-client-secret
OAUTH_REDIRECT_URI=http://localhost:8000/login/oauth/callback2. Create authentication routes:
Define routes in routes/web.php to redirect users to the OAuth provider and handle the callback.
use App\Http\Controllers\Auth\LoginController;
Route::get('login/oauth', [LoginController::class, 'redirectToProvider']);
Route::get('login/oauth/callback', [LoginController::class, 'handleProviderCallback']);3. Implement controller methods:
Add the following logic to app/Http/Controllers/Auth/LoginController.php to handle redirection and token exchange.
public function redirectToProvider()
{
$query = http_build_query([
'client_id' => env('OAUTH_CLIENT_ID'),
'redirect_uri' => env('OAUTH_REDIRECT_URI'),
'response_type' => 'code',
'scope' => '',
]);
return redirect('http://your-oauth-server.com/oauth/authorize?' . $query);
}
public function handleProviderCallback(Request $request)
{
$http = new GuzzleHttp\Client;
$response = $http->post('http://your-oauth-server.com/oauth/token', [
'form_params' => [
'grant_type' => 'authorization_code',
'client_id' => env('OAUTH_CLIENT_ID'),
'client_secret' => env('OAUTH_CLIENT_SECRET'),
'redirect_uri' => env('OAUTH_REDIRECT_URI'),
'code' => $request->code,
],
]);
$accessToken = json_decode((string) $response->getBody(), true)['access_token'];
// Use this access token to make authenticated API requests
}Testing the Implementation
1. Start the application: Run php artisan serve and navigate to http://localhost:8000/login/oauth to trigger the SSO flow.
2. Monitor and verify the flow: Ensure the user is redirected to the OAuth provider, receives an access token upon successful login, and is redirected back to the Laravel app.
Common Issues & Troubleshooting
Invalid credentials: Verify the client ID and secret in the .env file match the values provided by the OAuth2 provider.
Redirect URI mismatch: Ensure the redirect URI registered with the OAuth2 provider exactly matches the one defined in .env .
Conclusion
Integrating OAuth2 SSO into a Laravel application streamlines authentication across multiple services, significantly improving security and user experience. By following this guide, you have deployed a complete OAuth2 SSO setup. For advanced configurations, refer to the official Laravel Passport documentation.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.