Loading...

Login with Microsoft Graph

David Carr

5 min read - 30th Dec, 2020

In this post, I'll explain the process of using Microsoft Graph as a login process to allow users who have a Microsoft 365 account to login to a Laravel application, upon logging in a new user account would be created.

In order to use this you will need a Microsoft 365 account and to register an application in Azure.

First, you will need to register an application at https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps

Click New Registration, on the next page, enter the app name, I usually call the app the name of the project I'm working on.

Select the account type, for this tutorial select Accounts in this organizational directory only. This will allow only uses in your organisation to login and no one else.

Next enter the redirect url I like to redirect to a /connect endpoint:

Click reigster for the application to be created. You will then be directed to the application details page at the top of this page there is a Directory (tenant) ID take a note of both the client ID and the tenant ID both of these will be needed in your .env file.

Next, click on Certificates & secrets in the side menu. Then click New client secret enter the name of your application and the duration, I always select never to the secret does not expire. again take a note of the secret, it will be needed in your .env file.

Next, click on API Permissions, here is where you set the scopes your app will use. The default permissions will have already been set for Microsoft Graph are User.Read add any additional permissions you require. 

We are done with the app registration now we need to install a package called Laravel Microsoft Graph  

Install the package with composer:

composer require dcblogdev/laravel-microsoft-graph

Now publish the config file:

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

Publish the migration:

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

Publish the listener

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

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. 

After the migration has been published you can create the tokens tables by running the migration:

php artisan migrate

Now open .env and enter the following:

Enter the ids from the Application registration you created earlier, change the URLs to match your own.

MSGRAPH_CLIENT_ID=
MSGRAPH_SECRET_ID=
MSGRAPH_TENANT_ID=
MSGRAPH_OAUTH_URL=http://domain.com/connect
MSGRAPH_LANDING_URL=http://domain.com/app

Our landing page will be /app this is the page that can be accessed once logged in. /connect will initiate the login process.

 

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');

 

 

 

 

 

 

 

0 comments
Add a comment