Sign in with Microsoft Account with PHP

Sign in with Microsoft Account with PHP
Sign in with Microsoft Account with PHP thumbnail

Microsoft holds around 75 millions user accounts inside their fence.

This project concerns itself with implementing the OAuth 2.0 connection to their OAuth server in order to fetch authenticated user information.

In this project, we will only fetch normal login information like name and email.

For instructions, please refer to the video tutorial below.

Index.php
contains Sign in with Microsoft button

<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sign in with Microsofttitle>
head>
<body>
<a href="/signin.php">Sign in with Microsofta>
body>
html>
view raw index.php hosted with ❤ by GitHub

Signin.php
contains flow of initialization of OAuth 2.0 with Microsoft

session_start();
require "vendor/autoload.php";
use myPHPnotes\Microsoft\Auth;
$tenant = "common";
$client_id = "f6e12fd3-c628-4694-9c44-290e89e71543";
$client_secret = "s_cB1Aj-0I.0XWa3eVJ6SSf~1EQS3E5r~3";
$callback = "http://localhost:8080/callback.php";
$scopes = ["User.Read"];
$microsoft = new Auth($tenant, $client_id, $client_secret,$callback, $scopes);
header("location: " . $microsoft->getAuthUrl());
view raw signin.php hosted with ❤ by GitHub

Callback.php
the callback/redirection takes place to this script. It handles generating access token from authorization code and fetches user information against it.

use myPHPnotes\Microsoft\Auth;
use myPHPnotes\Microsoft\Handlers\Session;
use myPHPnotes\Microsoft\Models\User;
session_start();
require "vendor/autoload.php";
$auth = new Auth(Session::get("tenant_id"), Session::get("client_id"), Session::get("client_secret"), Session::get("redirect_uri"), Session::get("scopes"));
$tokens = $auth->getToken($_REQUEST['code'], $_REQUEST['state']);
$accessToken = $tokens->access_token;
$auth->setAccessToken($accessToken);
$user = new User;
echo "Name: " . $user->data->getDisplayName() . "
"
;
echo "Email: " . $user->data->getUserPrincipalName() . "
"
;
view raw callback.php hosted with ❤ by GitHub

Composer.json
Contains the library needed to make this function.

{
"require": {
"adnanhussainturki/microsoft-api-php": "^0.03.0"
}
}
view raw composer.json hosted with ❤ by GitHub

Source Code

Wrapper Git

Related Video:

Previous post
Multi Authentication System in Laravel 8
Next post
Book Review System in PHP