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> |
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()); |
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() . " "; |
Composer.json
Contains the library needed to make this function.
{ | |
"require": { | |
"adnanhussainturki/microsoft-api-php": "^0.03.0" | |
} | |
} |
Related Video: