Microsoft Entra: SSO design from the start
Microsoft Entra SSO using PHP or Javascript
Here’s how you can implement Single Sign-On (SSO) authentication and authorization with Microsoft Entra ID (formerly Azure AD) in PHP and JavaScript.
PHP Code Example
Using the Microsoft Authentication Library (MSAL) or OAuth 2.0 endpoints:
Dependencies
- Install a library like
league/oauth2-client
via Composer:composer require league/oauth2-client
Code
<?php
require 'vendor/autoload.php';
use League\OAuth2\Client\Provider\GenericProvider;
session_start();
// Replace with your Microsoft Entra (Azure AD) app details
$clientId = 'YOUR_CLIENT_ID';
$clientSecret = 'YOUR_CLIENT_SECRET';
$tenantId = 'YOUR_TENANT_ID';
$redirectUri = 'https://your-app-url.com/callback';
$provider = new GenericProvider([
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'redirectUri' => $redirectUri,
'urlAuthorize' => "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/authorize",
'urlAccessToken' => "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token",
'urlResourceOwnerDetails' => '',
'scopes' => ['openid', 'profile', 'email']
]);
// Handle the OAuth 2.0 Authorization Flow
if (!isset($_GET['code'])) {
$authorizationUrl = $provider->getAuthorizationUrl();
$_SESSION['oauth2state'] = $provider->getState();
header('Location: ' . $authorizationUrl);
exit;
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
unset($_SESSION['oauth2state']);
exit('Invalid state');
} else {
try {
$accessToken = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// Use the access token to get the user's profile
$request = $provider->getAuthenticatedRequest(
'GET',
'https://graph.microsoft.com/v1.0/me',
$accessToken
);
$response = $provider->getResponse($request);
$userData = $response->getBody()->getContents();
echo $userData;
} catch (\League\OAuth2\Client\Provider\Exception\IdentityProviderException $e) {
exit($e->getMessage());
}
}
JavaScript Example
Using Microsoft Authentication Library (MSAL.js) for front-end authentication:
Dependencies
Install MSAL.js using npm or include it via a CDN:
npm install @azure/msal-browser
Or include via a script tag:
<script src="https://alcdn.msauth.net/browser/2.32.0/js/msal-browser.min.js"></script>
Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Microsoft Entra Authentication</title>
</head>
<body>
<button id="login">Login with Microsoft</button>
<button id="logout">Logout</button>
<div id="user-info"></div>
<script>
const msalConfig = {
auth: {
clientId: "YOUR_CLIENT_ID",
authority: "https://login.microsoftonline.com/YOUR_TENANT_ID",
redirectUri: "https://your-app-url.com",
}
};
const msalInstance = new msal.PublicClientApplication(msalConfig);
document.getElementById('login').onclick = async () => {
try {
const loginResponse = await msalInstance.loginPopup({
scopes: ["user.read"]
});
console.log('Login successful:', loginResponse);
const account = msalInstance.getAllAccounts()[0];
const tokenResponse = await msalInstance.acquireTokenSilent({
account,
scopes: ["user.read"]
});
const userResponse = await fetch('https://graph.microsoft.com/v1.0/me', {
headers: {
'Authorization': `Bearer ${tokenResponse.accessToken}`
}
});
const userData = await userResponse.json();
document.getElementById('user-info').innerText = `Hello, ${userData.displayName}`;
} catch (error) {
console.error('Error during login:', error);
}
};
document.getElementById('logout').onclick = () => {
msalInstance.logout();
};
</script>
</body>
</html>
Key Components
- Scopes: Both implementations request
openid
,profile
, andemail
(and optionallyuser.read
for MS Graph API). - Microsoft Graph API: Used to fetch user profile data after successful authentication.
- OAuth 2.0 Flow: PHP demonstrates the backend handling of OAuth 2.0, while JavaScript uses the front-end MSAL.js library.
Replace placeholders (YOUR_CLIENT_ID
, YOUR_CLIENT_SECRET
, YOUR_TENANT_ID
, etc.) with your actual Microsoft Entra app details.
Here are references for the PHP and JavaScript implementations provided:
PHP Implementation References
- Microsoft Authentication Library (MSAL) for PHP:
- Microsoft Entra (Azure AD) OAuth 2.0 Endpoints:
- Microsoft Graph API:
- PHP Example of Microsoft Graph API with OAuth:
JavaScript Implementation References
- MSAL.js (Microsoft Authentication Library):
- Using MSAL.js with Azure AD:
- Microsoft Identity Platform Documentation:
- Example JavaScript Application:
- Microsoft Graph JavaScript SDK:
General Resources
- OAuth 2.0 and OpenID Connect:
These references provide the foundational knowledge and detailed steps to implement SSO with Microsoft Entra (Azure AD) in your applications.