Login with MsGraph

This guide will show a process of using MsGraph an authentication service for a fresh Laravel 8 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

MSGRAPH_CLIENT_ID=
MSGRAPH_SECRET_ID=
MSGRAPH_TENANT_ID=

MSGRAPH_OAUTH_URL=https://project.com/connect
MSGRAPH_LANDING_URL=https://project.com/app
MSGRAPH_PREFER_TIMEZONE='outlook.timezone="Europe/London"'

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:

<?php

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;
            $token->save();

            Auth::login($user);

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

            Auth::login($user);
        }
    }
}

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. 

 

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'], 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.

This has three methods:

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

Connect - when called will redirect to Microsoft Graph login page

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

<?php

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>
    </div>

    <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">
                <div class="py-1"><svg class="fill-current h-6 w-6 text-yellow-500 mr-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M2.93 17.07A10 10 0 1 1 17.07 2.93 10 10 0 0 1 2.93 17.07zm12.73-1.41A8 8 0 1 0 4.34 4.34a8 8 0 0 0 11.32 11.32zM9 11V9h2v6H9v-4zm0-6h2v2H9V5z"/></svg></div>
                <div>
                    <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>
                </div>
            </div>
        </div>

        <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>

    </div>

</div>

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

MsGraph::get('me');

 

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

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