Login with MsGraph

This guide will show a process of using MsGraph an authentication service for a fresh Laravel install. No Auth package will be installed and no user authentication system will be built, instead, the entire authentication system will be offloaded to Microsoft Graph.

This means all users will already be connected to Microsoft Graph and all login, 2FA, and password reset will be handled by Microsoft Graph entirely. Your application can then allow logins using Microsoft Graph.

MsGraph will tie into Laravel's Auth system allowing the usage of @auth blade directives and Auth:: calls.

Install the package

See Install page for the full install instructions

Set the .env variables: make sure to fill these in



publishing the config:

php artisan vendor:publish --provider="Dcblogdev\MsGraph\MsGraphServiceProvider" --tag="config"

Next, publish the migrations

php artisan vendor:publish --provider="Dcblogdev\MsGraph\MsGraphServiceProvider" --tag="migrations"

Publish the listener, this is required for logging in 

php artisan vendor:publish --provider="Dcblogdev\MsGraph\MsGraphServiceProvider" --tag="Listeners"

This will publish the following code into app/Listeners/NewMicrosoft365SignInListener.php file contain:


namespace App\Listeners;

use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Dcblogdev\MsGraph\Models\MsGraphToken;
use Illuminate\Support\Facades\Auth;

class NewMicrosoft365SignInListener
    public function handle($event)
        $tokenId = $event->token['token_id'];
        $token = MsGraphToken::find($tokenId)->first();

        if ($token->user_id == null) {
            $user = User::firstOrCreate([
                'name'  => $event->token['info']['displayName'],
                'email' => $event->token['info']['mail'],
                'password' => ''

            $token->user_id = $user->id;


        } else {
            $user = User::findOrFail($token->user_id);


This runs when a successful login is made from the package, this code can be changed to suit your needs. A new user will be created in the user's table if they do not exist otherwise the user instance will be returned. The MsGraph token will be linked to the user and then logged in using Auth::login($user). From this point there normal Laravel Auth helpers/blade directives are available. 

Record the listeners in EventServiceProvider

Import the 2 events

use App\Listeners\NewMicrosoft365SignInListener;
use Dcblogdev\MsGraph\Events\NewMicrosoft365SignInEvent;

In the boot method add:

public function boot()
        [NewMicrosoft365SignInListener::class, 'handle']

Setting the routes in routes/web.php

Create a login and connect route that loads a AuthController file.

The login route loads a method that in turn loads a view

Route::redirect('/', 'login');

Route::group(['middleware' => ['web', 'guest'], 'namespace' => 'App\Http\Controllers\Auth'], function(){
    Route::get('login', 'AuthController@login')->name('login');
    Route::get('connect', 'AuthController@connect')->name('connect');

Route::group(['middleware' => ['web', 'MsGraphAuthenticated'], 'prefix' => 'app', 'namespace' => 'App\Http\Controllers'], function(){
    Route::get('/', 'PagesController@app')->name('app');
    Route::get('logout', 'Auth\AuthController@logout')->name('logout');

The second group of routes run when a user is connected to MsGraph the middleware MsGraphAuthenticated is used to ensure the route won't run unless connected.

Create a controller called AuthController inside App\Http\Controllers\Auth.

This has three methods:

Login - loads a view to informing the user to log in with their Microsoft Account

Connect - when called will redirect to the Microsoft Graph login page

Logout - will disconnect from MsGraph and redirect to the desired page.


namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Dcblogdev\MsGraph\Facades\MsGraph;

class AuthController extends Controller
    public function login()
        return view('auth.login');

    public function connect()
        return MsGraph::connect();

    public function logout()
        return MsGraph::disconnect('/');

Next, create the view auth/login.blade.php, this page uses TailwindCSS for styling but is not required.

This page loads when visiting /login and informs the guest to login with their Microsoft account, clicking the login button will redirect to /connect where the Microsoft Graph login page will be loaded.

<div class="bg-gray-200 dark:bg-gray-700 dark:text-white min-h-screen py-32 px-10">

    <div class="text-center mb-10 md:w-3/4 lg:w-1/2 mx-auto">
        <div class="text-5xl tracking-tight leading-10 font-extrabold text-gray-900 dark:text-white">
            {{ config('app.name') }}

    <div class="bg-white dark:bg-gray-600 p-10 rounded-lg shadow-lg w-full lg:w-1/3 mx-auto">

        <div class="bg-yellow-100 border-t-4 border-yellow-500 rounded-b text-yellow-900 px-4 py-3 shadow-md" role="alert">
            <div class="flex">
                    <p class="font-bold">We use Microsoft 365 for accessing your account.</p>
                    <p class="text-sm">Click the button below to get started.</p>

        <p><a class="mt-5 w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500" href="{{ route('connect') }}">Login with your Microsoft Account</a></p>



Once logged in the normal usage of MsGraph applies, ie to call the users details you can call:



Help support the blog so that I can continue creating new content!

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2022 DC Blog. All code MIT license. All rights reserved.