Microsoft Authentication Implement on Laravel App

  • 27-08-2022
  • 5161
  • Laravel 9
  • Haresh Chauhan

Microsoft authenticator login laravel, In this article we will teach you how to make Microsoft authenticator in laravel application by installing composer package adnanhussainturki/microsoft-api-php.

Microsoft login azure, we will first install composer adnanhussainturki/microsoft-api-php in our application, then after we will route for the handle all the login HTTP requests. we will also create a login controller for the handle route method in the controller.

Microsoft Authentication on Laravel App, we will get all the credentials from the Microsoft portal and set them in our .env file. as well as we will test in the local server.

So let's start to implement Microsoft authenticator on the laravel app.

Step 1. Create Laravel Project

Let's start by cloning a new laravel application. Use the below-provided command, Also you may change the project name as per your requirement. Goto the terminal and run the command.

composer create-project --prefer-dist laravel/laravel microsoft-auth

Go to your project directory using "cd" and then give your project name and hit enter in your terminal.

cd microsoft-auth

Step 2. Composer Install

Goto in your composer.json file. add "adnanhussainturki/microsoft-api-php": "^0.03.0" in your framework require option. just open your composer. json file and paste below given code into your JSON file.

Composer.json
{
    "require": {
        "adnanhussainturki/microsoft-api-php": "^0.03.0"
    }
}

Once you pasted the package name in your composer file run the below provided command in your application terminal.

Laravel-9 Multi Authentication Guard Passport API Example

composer install

Step 3. Set Configuration

Open your .env file. You will find the root of the project and paste below the given key name in your .env file at the end. then generate credentials from the Microsoft account and set them in given keys.

.env
# MICROSOFT CREDENTIAL
TENANT_ID='your_tenant_id'
CLIENT_ID='your_client_id'
CLIENT_SECRET='your_client_secret'
CALLBACK_URL='your_callback_url'

Clear config cache issue, It sometimes happens that the after-added configuration into the config file not working.

php artisan config:cache
php artisan config:clear

Step 4. Routes

Create a controller using the below command. I am creating MicrosoftAuthController the handle HTTP request.

php artisan make:controller MicrosoftAuthController

Import MicrosoftAuthController at the top of the web.php file. create three routes for the make Microsoft login request handle.

The first route for the view sign in form. The second route for the send login request to the microsoft auth access. The third route for the handel callback request form the microsoft auth login.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Front\MicrosoftAuthController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

// MICROSOFT LOGIN
Route::get('/',[MicrosoftAuthController::class,'signInForm'])->name('sign.in');
Route::get('microsoft-oAuth',[MicrosoftAuthController::class,'microsoftOAuth'])->name('microsoft.oAuth');
Route::get('callback',[MicrosoftAuthController::class,'microsoftOAuthCallback'])->name('microsoft.oAuth.callback');

Step 5. MicrosoftAuthController

The first method for the view sign is in the blade file. The second method for the send auth login request to Microsoft. This method is for the handle callback request from the Microsoft login auth.

MicrosoftOAuth method we will make a login request. For making a login request we will first import use myPHPnotes\Microsoft\Auth;, call the auth, and pass all the given credentials in this call. In return response, this class will make auth requests and redirect to Microsoft login screen.

Once you enter your email address and password in the auth login screen and submit it will require to microsoftOAuthCallback method, again we will call auth class and get an access token from there and also get user profile details from the new User class.

app/Http/Controllers/MicrosoftAuthController.php
<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use myPHPnotes\Microsoft\Auth;
use myPHPnotes\Microsoft\Models\User;

class MicrosoftAuthController extends Controller
{
    public function signInForm()
    {
        return view('front.sign-in');
    }

    public function microsoftOAuth()
    {
        $microsoft = new Auth(env('TENANT_ID'),env('CLIENT_ID'),env('CLIENT_SECRET'),env('CALLBACK_URL') ,["User.Read"]);

        $url = $microsoft->getAuthUrl();

        return redirect($url);
    }

    public function microsoftOAuthCallback(Request $request)
    {
        $microsoft = new Auth(env('TENANT_ID'),env('CLIENT_ID'),env('CLIENT_SECRET'),env('CALLBACK_URL') ,["User.Read"]);

        $tokens = $microsoft->getToken($request->code);

        $accessToken = $tokens->access_token;

        $microsoft->setAccessToken($accessToken);

        $user = new User;

        $name = $user->data->getDisplayName();
        $email = $user->data->getUserPrincipalName();

        dd($name,$email);
    }
}

Step 6. Blade File

Blade file for the view sign-in button show. As you will click on the sign-in button you will redirect to the Microsoft auth screen. This blade file is just for the send to the Microsoft.

resources/views/front/sign-in.blade.php
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <title>Hello, world!</title>
</head>
<body>
    <a class="btn btn-success" href="{{ route('microsoft.oAuth') }}">Sign In</a>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Step 7. Start Development Server

Start your application development server by the suggested command in your terminal.

php artisan serve

Open your browser, and run the below-given URL in your browser.

http://127.0.0.1:8000/

Laravel 9 Create Custom Auth Guard Multi Login Authentication System Tutorial


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :