laravelmicrosoft-graph-apisingle-sign-onlaravel-socialitemicrosoft-account

Add Microsoft account login in Laravel application


I currently have a web application made with Laravel, which already has the standard login system provided by Laravel.

I would like to add the option of being able to log into the application also through a Microsoft 365 account, for those users who have it.

I have been searching in Google and I have found some interesting pages where it is explained how to log in with a Microsoft account (with Microsoft Graph), like for example the following one:

https://dcblog.dev/login-with-microsoft-graph

However, in this tutorial (and in all the others I have found), they propose a login exclusively through the Microsoft account (unless I am wrong).

What I need is not to replace the current login in the application with a Microsoft login, but to add this second option and allow the user to log in both ways.

My doubt is because the problem I see is that in the tutorials I have seen, a migration of the user table is created from scratch, when in my case I already have a users table. I don't know how I should act in this sense, since (I think) at first I don't think it is necessary to have another user table for logging into the application, but simply send the necessary parameters (tenant, client_id, client_secret,...) to Microsoft and get a success/error response.

Please, I would appreciate some help in this regard in order to move forward, as I am completely stuck and cannot find a solution.

Thank you very much in advance.


Solution

  • Install Laravel Socialite and Microsoft Provider:

    https://laravel.com/docs/11.x/socialite
    https://packagist.org/packages/socialiteproviders/microsoft
    

    By using composer:

    composer require laravel/socialite
    composer require socialiteproviders/microsoft
    

    Create two columns migrations for the users table:

    'microsoft_id',   
    'microsoft_token' 
    

    Add the Routings and define the function in the AuthController:

    Route::get('auth/microsoft', [AuthController::class, 'redirectToMicrosoft'])->name('microsoft.login');
    Route::get('auth/microsoft/callback', [AuthController::class, 'handleMicrosoftCallback']);
    

    Env configurations:

    MICROSOFT_CLIENT_ID=your_client_id
    MICROSOFT_CLIENT_SECRET=your_secret
    MICROSOFT_REDIRECT_URI=http://your-app.com/auth/microsoft/callback
    MICROSOFT_TENANT_ID=common
    

    Configure and check use case for both libraries as per the reference link. It will be helpful for you.