Implementing Microsoft Login in Laravel 10 Application with Fortify #
Social login has become an integral part of modern web applications. In this article, I’ll show you how to implement Microsoft account login in a Laravel 10 application using the Fortify package. We’ll go through the entire process step by step - from installing the necessary packages, through project configuration, to solving common problems.
Required Packages #
Let’s start by installing the necessary packages:
composer require laravel/socialite socialiteproviders/microsoft
Laravel Socialite is the official Laravel package for social login handling, while socialiteproviders/microsoft is an extension that adds support for Microsoft OAuth.
EventServiceProvider Configuration #
After installing the packages, we need to update our EventServiceProvider to handle Microsoft login. In the app/Providers/EventServiceProvider.php file, add the following code:
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
\SocialiteProviders\Manager\SocialiteWasCalled::class => [
\SocialiteProviders\Microsoft\MicrosoftExtendSocialite::class.'@handle',
],
];
Note: Pay special attention to the correct class name MicrosoftExtendSocialite. A common mistake is using the non-existent MicrosoftExtendedServiceProvider class.
Registering Application in Microsoft Azure #
To enable Microsoft login, we need to register our application in the Azure portal:
- Log in to Azure Portal
- Go to “Microsoft Entra ID” (formerly Azure Active Directory)
- Select “App registrations” → “New registration”
- Give your application a name
- Choose account type (usually “Accounts in any organizational directory and personal Microsoft accounts”)
- Set redirect URI:
https://your-domain.com/login/microsoft/callback - After registration, note the “Application (client) ID” and create a “Client secret”
The following instructional video shows in detail the process of registering an application in Microsoft Azure and configuring the necessary permissions:
This video is particularly helpful during first-time configuration, as the Azure Portal interface can be somewhat overwhelming for beginners.
Laravel Configuration #
Next, add the Microsoft OAuth configuration to the config/services.php file:
'microsoft' => [
'client_id' => env('MICROSOFT_CLIENT_ID'),
'client_secret' => env('MICROSOFT_CLIENT_SECRET'),
'redirect' => env('MICROSOFT_REDIRECT_URI'),
'tenant' => env('MICROSOFT_TENANT_ID', 'common'),
],
Update the .env file with the appropriate variables:
MICROSOFT_CLIENT_ID=your-client-id
MICROSOFT_CLIENT_SECRET=your-client-secret
MICROSOFT_REDIRECT_URI=https://your-domain.com/login/microsoft/callback
Updating the User Model #
To store Microsoft account information, we need to update the User model. First, let’s create a migration:
php artisan make:migration add_microsoft_auth_to_users_table
In the migration file, add the necessary columns:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->text('microsoft_id')->nullable();
$table->text('microsoft_token')->nullable();
$table->text('microsoft_refresh_token')->nullable();
$table->timestamp('token_expires_at')->nullable();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn([
'microsoft_id',
'microsoft_token',
'microsoft_refresh_token',
'token_expires_at'
]);
});
}
Note: Notice that we use the text type instead of string for fields storing tokens. OAuth tokens from Microsoft are quite long and may exceed the default 255 character length of a VARCHAR column.
Next, let’s update the User model in app/Models/User.php:
protected $fillable = [
'name',
'email',
'password',
'microsoft_id',
'microsoft_token',
'microsoft_refresh_token',
'token_expires_at'
];
/**
* Update Microsoft data for user
*/
public function updateMicrosoftData($microsoftUser)
{
$this->microsoft_id = $microsoftUser->getId();
$this->microsoft_token = $microsoftUser->token;
if (isset($microsoftUser->refreshToken)) {
$this->microsoft_refresh_token = $microsoftUser->refreshToken;
}
if (isset($microsoftUser->expiresIn)) {
$this->token_expires_at = now()->addSeconds($microsoftUser->expiresIn);
}
return $this->save();
}
Creating Routes #
Now let’s add routes to handle Microsoft login in the routes/web.php file:
use Laravel\Socialite\Facades\Socialite;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
Route::get('/login/microsoft', function () {
return Socialite::driver('microsoft')->redirect();
})->name('login.microsoft');
Route::get('/login/microsoft/callback', function () {
$microsoftUser = Socialite::driver('microsoft')->user();
// Check if user exists in database
$user = User::where('email', $microsoftUser->getEmail())->first();
// If user exists, update their Microsoft data and log them in
if ($user) {
$user->updateMicrosoftData($microsoftUser);
Auth::login($user);
return redirect()->intended('/dashboard');
}
// If user doesn't exist, redirect to login page with message
return redirect()->route('login')
->with('error', 'Account with this email address does not exist. Please register first.');
});
This implementation only checks if the user exists in the database without creating new accounts. If you want to enable account creation as well, you can modify the code:
// Alternative version enabling registration
if (!$user) {
$user = User::create([
'name' => $microsoftUser->getName(),
'email' => $microsoftUser->getEmail(),
'password' => Hash::make(Str::random(24)),
]);
}
Adding Login Button #
Finally, let’s add a Microsoft login button to our login form:
<a href="{{ route('login.microsoft') }}" class="btn btn-light">
<i class="fab fa-microsoft"></i> Login with Microsoft
</a>
Troubleshooting #
Token Length Issue #
One of the most common problems is an error related to the length of the token received from Microsoft:
SQLSTATE: String data, right truncated: 1406 Data too long for column 'microsoft_token'
If you encounter this problem and didn’t use the text type in the original migration, you can create a new migration that increases the column size:
php artisan make:migration increase_microsoft_token_column_size
In the migration file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class IncreaseMicrosoftTokenColumnSize extends Migration
{
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->text('microsoft_token')->change();
$table->text('microsoft_refresh_token')->nullable()->change();
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->string('microsoft_token')->change();
$table->string('microsoft_refresh_token')->nullable()->change();
});
}
}
To use the change() method in migrations, you need to install the package:
composer require doctrine/dbal
EventServiceProvider Class Issue #
A common mistake is the incorrect class name in EventServiceProvider. Make sure you use:
\SocialiteProviders\Microsoft\MicrosoftExtendSocialite::class.'@handle'
and not:
\SocialiteProviders\Microsoft\MicrosoftExtendedServiceProvider::class
Summary #
In this article, I showed how to implement Microsoft login in a Laravel 10 application with Fortify. The presented code can be easily adapted to your own needs, for example by adding more fields with user information or integrating login with other OAuth providers.
Such a solution increases the convenience of using the application and can significantly reduce the entry barrier for new users, especially in corporate environments where Microsoft accounts are common.
Remember that when implementing social login, it’s always worth ensuring appropriate security measures and testing various login scenarios before deploying to production.