At 2020 I started to study how to do a simple Azure AD Oauth2 authentication without the need to maintain the session and in overall no need for additional bells and whistles. First I of course ended up testing magium/active-directory , but it is a huge 10Mb package of code that is hard to validate and you need Composer to even install it properly that adds even more overhead that I just didn’t want to carry. After doing enough googling and concluding that there is no good example for PHP how to implement a single page authentication with Oauth2 like specified here, I decided to write my own targeted especially for Azure AD integration (after year 2023 known as Entra ID).
Before going into my example, I need to state that there are nice examples for many programming languages available from Microsoft and other tools and documentation that I find useful:
Here is my heavily commented example code:
<?php
//This login script is based on Sami Sipponen's Simple Entra ID Oauth2 Example with PHP:
//https://www.sipponen.com/archives/4024
session_start(); //Since you likely need to maintain the user session, let's start it an utilize it's ID later
error_reporting(-1); //Remove from production version
ini_set("display_errors", "on"); //Remove from production version
//Configuration, needs to match with Azure app registration
$client_id = "00000000-0000-0000-0000-000000000000"; //Application (client) ID
$ad_tenant = "00000000-0000-0000-0000-000000000000"; //Entra ID Tenant ID, with Multitenant apps you can use "common" as Tenant ID, but using specific endpoint is recommended when possible
$client_secret = "entra-app-secret-from-your-app-registration"; //Client Secret, remember that this expires someday unless you haven't set it not to do so
$redirect_uri = "https://your-server.your-domain.com/this-page.php"; //This needs to match 100% what is set in Entra ID
$error_email = "your.email@your-domain.com"; //If your php.ini doesn't contain sendmail_from, use: ini_set("sendmail_from", "user@example.com");
function errorhandler($input, $email)
{
$output = "PHP Session ID: " . session_id() . PHP_EOL;
$output .= "Client IP Address: " . getenv("REMOTE_ADDR") . PHP_EOL;
$output .= "Client Browser: " . $_SERVER["HTTP_USER_AGENT"] . PHP_EOL;
$output .= PHP_EOL;
ob_start(); //Start capturing the output buffer
var_dump($input); //This is not for debug print, this is to collect the data for the email
$output .= ob_get_contents(); //Storing the output buffer content to $output
ob_end_clean(); //While testing, you probably want to comment the next row out
mb_send_mail($email, "Your Entra ID Oauth2 script faced an error!", $output, "X-Priority: 1\nContent-Transfer-Encoding: 8bit\nX-Mailer: PHP/" . phpversion());
echo "<p>" . $input["Description"] . "</p>" . PHP_EOL;
exit;
}
if (isset($_GET["code"])) echo "<pre>"; //This is just for easier and better looking var_dumps for debug purposes
if (!isset($_GET["code"]) and !isset($_GET["error"])) { //Real authentication part begins
//First stage of the authentication process; This is just a simple redirect (first load of this page)
$url = "https://login.microsoftonline.com/" . $ad_tenant . "/oauth2/v2.0/authorize?";
$url .= "state=" . session_id(); //This at least semi-random string is likely good enough as state identifier
$url .= "&scope=User.Read"; //This scope seems to be enough, but you can try "&scope=profile+openid+email+offline_access+User.Read" if you like
$url .= "&response_type=code";
$url .= "&approval_prompt=auto";
$url .= "&client_id=" . $client_id;
$url .= "&redirect_uri=" . urlencode($redirect_uri);
header("Location: " . $url); //So off you go my dear browser and welcome back for round two after some redirects at Entra ID's end
} elseif (isset($_GET["error"])) { //Second load of this page begins, but hopefully we end up to the next elseif section...
echo "Error handler activated:\n\n";
var_dump($_GET); //Debug print
errorhandler(array("Description" => "Error received at the beginning of second stage.", "\$_GET[]" => $_GET, "\$_SESSION[]" => $_SESSION), $error_email);
} elseif (strcmp(session_id(), $_GET["state"]) == 0) { //Checking that the session_id matches to the state for security reasons
echo "Stage2:\n\n"; //And now the browser has returned from its various redirects at Entra ID's side and carrying some gifts inside $_GET
var_dump($_GET); //Debug print
//Verifying the received tokens with Azure and finalizing the authentication part
$content = "grant_type=authorization_code";
$content .= "&client_id=" . $client_id;
$content .= "&redirect_uri=" . urlencode($redirect_uri);
$content .= "&code=" . $_GET["code"];
$content .= "&client_secret=" . urlencode($client_secret);
$options = array(
"http" => array( //Use "http" even if you send the request with https
"method" => "POST",
"header" => "Content-Type: application/x-www-form-urlencoded\r\n" .
"Content-Length: " . strlen($content) . "\r\n",
"content" => $content
)
);
$context = stream_context_create($options);
$json = @file_get_contents("https://login.microsoftonline.com/" . $ad_tenant . "/oauth2/v2.0/token", false, $context); //You may want to remove @ to see more details from PHP's log
if ($json === false) {
$error = error_get_last();
if (str_contains(strtolower($error['message']), 'failed to open stream')) {
errorhandler(array("Description" => "Error received during Bearer token fetch. For some reason this page was not able to connect Entra, usually this happens because of a certificate validation issue that starts to work after you have visited <a href=\"https://portal.office.com\">portal.office.com</a>.", "PHP_Error" => $error, "\$_GET[]" => $_GET, "HTTP_msg" => $options));
} else {
errorhandler(array("Description" => "Error received during Bearer token fetch. You probably reloaded the Entra ID login page with parameters in URL and that will not work.", "PHP_Error" => $error, "\$_GET[]" => $_GET, "HTTP_msg" => $options));
}
}
$authdata = json_decode($json, true);
if (isset($authdata["error"])) errorhandler(array("Description" => "Bearer token fetch contained an error.", "\$authdata[]" => $authdata, "\$_GET[]" => $_GET, "HTTP_msg" => $options), $error_email);
var_dump($authdata); //Debug print
//Fetching the basic user information that is likely needed by your application
$options = array(
"http" => array( //Use "http" even if you send the request with https
"method" => "GET",
"header" => "Accept: application/json\r\n" .
"Authorization: Bearer " . $authdata["access_token"] . "\r\n"
)
);
$context = stream_context_create($options);
$json = @file_get_contents("https://graph.microsoft.com/v1.0/me", false, $context); //You may want to remove @ to see more details from PHP's log
if ($json === false) errorhandler(array("Description" => "Error received during user data fetch.", "PHP_Error" => error_get_last(), "\$_GET[]" => $_GET, "HTTP_msg" => $options), $error_email);
$userdata = json_decode($json, true); //This should now contain your logged on user information
if (isset($userdata["error"])) errorhandler(array("Description" => "User data fetch contained an error.", "\$userdata[]" => $userdata, "\$authdata[]" => $authdata, "\$_GET[]" => $_GET, "HTTP_msg" => $options), $error_email);
var_dump($userdata); //Debug print
} else {
//If we end up here, something has obviously gone wrong... Likely a hacking attempt since sent and returned state aren't matching and no $_GET["error"] received.
echo "Hey, please don't try to hack us!\n\n";
echo "PHP Session ID used as state: " . session_id() . "\n"; //And for production version you likely don't want to show these for the potential hacker
var_dump($_GET); //But this being a test script having the var_dumps might be useful
errorhandler(array("Description" => "Likely a hacking attempt, due state mismatch.", "\$_GET[]" => $_GET, "\$_SESSION[]" => $_SESSION), $error_email);
}
echo "\n<a href=\"" . $redirect_uri . "\">Click here to redo the authentication</a>"; //Only to ease up your tests
?>
The code above for sure is not implementing everything defined by Oauth2 standard, but it seems to do its job. If you plan to use it for something else than just testing, please remove the unnecessary var_dumps and echo “<pre>” from the beginning of the script and of course add the things needed for your application.
The final array $userdata will look like this: (copy & paste from Microsoft’s Graph Explorer test account output)
{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
"businessPhones": [
"+1 412 555 0109"
],
"displayName": "Megan Bowen",
"givenName": "Megan",
"jobTitle": "Auditor",
"mail": "MeganB@M365x214355.onmicrosoft.com",
"mobilePhone": null,
"officeLocation": "12/1110",
"preferredLanguage": "en-US",
"surname": "Bowen",
"userPrincipalName": "MeganB@M365x214355.onmicrosoft.com",
"id": "48d31887-5fad-4d73-a9f5-3c356e68a038"
}
At Entra ID you need to make an app registration that matches to your application. Here is how to do that:
- Just open https://aad.portal.azure.com or https://portal.azure.com and open “Microsoft Entra ID” there.
- From left menu under Manage section open “App registrations”.
- Next click “+ New registration” from the top of the view you just opened.
- Now you can enter the name of your application and select is your app Single tenant or Multitenant app. And this selection of course depends how publicly you mean to share this application. If you are unsure, select Single tenant to be at the safe side. You can change this later if needed from “Authentication” page. The most important thing in this view is to give the Redirect URI to your authentication page (the page that contains my example code). This needs to be secured with HTTPS, so don’t even bother trying with just http://, since it will not work. However this URL does not need to be publicly available since it is accessed by your browser, not by Entra ID itself, so even localhost will work as long as you have https:// connection to it.
- Since you now have the app registration created and you are in “Overview” page, please copy your Application (client) ID and Directory (tenant) ID, since you will need those with my example code.
- And now you are almost ready! There is only the one final thing to do, which is creating the “Client secret” for your registered app. Click “Certificates & secrets” from left menu and from the page that opens click “+New client secret” button. Now you can give some description if you like, but the main thing here is to select how long your secret is valid. After you have selected, just click “Add” button and there you have it. Please note that Azure will not show the secret to you afterwards, so you need to copy it now to a safe place or to create a new one if you lost it.
Since I’m too lazy to take screenshots and blurring out the sensitive content, here is Microsoft’s documentation how to create the App registration, this covers bullets 1-5 from above: https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-ap
The only thing this guide does not show is the Client Secret creation, but that is only couple of clicks and instructed in the last bullet (6).
If you need to get also user groups listed, that is rather easy with:
$options = array(
"http" => array( //Use "http" even if you send the request with https
"method" => "GET",
"header" => "Accept: application/json\r\n" .
"Authorization: Bearer " . $authdata["access_token"] . "\r\n"
)
);
$context = stream_context_create($options);
$json = file_get_contents("https://graph.microsoft.com/v1.0/me/memberOf", false, $context);
if ($json === false) errorhandler(array("Description" => "Error received during user group data fetch.", "PHP_Error" => error_get_last(), "\$_GET[]" => $_GET, "HTTP_msg" => $options), $error_email);
$groupdata = json_decode($json, true); //This should now contain your logged on user memberOf (groups) information
if (isset($groupdata["error"])) errorhandler(array("Description" => "Group data fetch contained an error.", "\$groupdata[]" => $groupdata, "\$authdata[]" => $authdata, "\$_GET[]" => $_GET, "HTTP_msg" => $options), $error_email);
Locate the above code for example after $userdata section. Please notice that you will need to add slightly more permissions to your app registration or else you will get “empty” array as return:
- Open your app registration and API permissions page.
- Click “+Add a permission” button.
- Select “Microsoft Graph” and then “Delegated permissions”.
- Next you need to expand “Group” section and select “Group.Read.All” permission. Click “Add permissions” button from the bottom.
- The final thing needed is to grant admin consent to your application, where you obviously need high enough permissions to your Entra ID to do so (application admin RBAC role is enough).
When mapping the user groups to your application, likely the best attributes for that are onPremisesSecurityIdentifier or securityIdentifier. At least these should not break up easily during the time. If you need to see an example output from https://graph.microsoft.com/v1.0/me/memberOf, just use the Graph Explorer to get it.
Quick way to inject the login data into your $_SESSION variables:
//This replaces all previous data in your session, but during login process you likely want to do that
$_SESSION = $userdata;
$_SESSION["oauth_bearer"] = $authdata["access_token"];
$_SESSION["groups"] = $groupdata;
More information about PHP session variable from:
https://www.php.net/manual/en/reserved.variables.session.php
12.08.2021 Update:
Even there is usually no issues at all to execute the login process just by redirecting the browser to the login page, sometimes the user session with Entra ID is somehow broken and needs to be refreshed. At such case the login process ends up to bearer token fetch error even everything should be pretty much ok… It starts to work if the user visits some O365 page like portal.office.com or closes the browser and opens it again. I have not figured out why this happens, but I would recommend using AAD to trigger the login process instead of your own login page, which should mitigate the issue. So instead of using the URL of your own login page to trigger the login process, try to use this:
https://account.activedirectory.windowsazure.com/applications/signin/<YOUR_APP_ID_HERE_=_$client_id>?tenantId=<YOUR_TENANT_ID_HERE_=_$ad_tenant>
For above to work you need to specify the full URL of your own login page to Entra ID application registration settings. This can be done from “Branding” blade at portal with “Home page URL” field. Please note that instead of just specifying the homepage you really need to use full URL to your actual login page.
The additional benefit of doing this is that your application will be working from portal.office.com in case someone clicks it from there:
https://www.office.com/apps?auth=2
25.03.2022 Update:
In case you need some other attributes from the user object that are not coming with “/me” by default, you can use $select argument at line 74 to select the properties you need, like on-premises AD username details:
https://graph.microsoft.com/v1.0/me?$select=userPrincipalName,onPremisesSamAccountName,onPremisesDomainName
Note that you might want to check are onPremisesSamAccountName and onPremisesDomainName empty with your PHP code, so don’t trust that all Entra ID users have those attributes available.
And please remember that the Graph Explorer is your friend to find out what attributes are available, especially if you login to it with your own account so that you can see your own user account data with it. There are quite a lot of properties that you can get: https://docs.microsoft.com/en-us/graph/api/resources/user?view=graph-rest-1.0#properties (and your own custom attributes on top of these if you have some)
01.04.2024 Update:
Some changes made to reflect Azure AD name change as Entra ID + updated above example how to get on-prem AD details. And no, this is not april fool’s post even the day happens to be it. 🙂
02.10.2024 Update:
Slightly improved error reporting for bearer token fetch phase and mitigated PHP warning going into logs. Sometimes there seem to be a problem to validate Microsoft’s Oauth certificate that disappears when user visits some Microsoft page like portal.office.com. Note that the error appearing in the email about failed to open stream is not the only one, and there are more explaining warnings going into PHP log if you remove “@” character from file_get_contents function.
Disclaimer and Licensing:
There is no license for this code, since it has been meant just as an example. Without modifications and embedding it as part of your software this does not bring much value. Feel free to utilize it as you like, even commercially, but please remember that I’m not taking any responsibility of this code, meaning use at your own risk. If you find a bug or security issue with it, please drop me an email to sami@sipponen.com. In case you like the script, maybe you leave the top comments in place about the origin of the script, but that is not mandatory either.