A while ago I wrote some code to enable one of my PHP projects to log in via authentication with ADFS. I’ve recently updated this to talk directly with Azure AD, and have split this off into a separate project which I’ll share here.
Basically this works using oAuth2, browser sessions, a database and a couple of scripts, and on the Azure AD side you need to create an App Registration. Within this sample project the following flow happens:
- User lands on index.php. If they do not have a session key cookie, one is generated, and this is stored in the database along with the page the user was attempting to access. They are redirected to login.microsoftonline.com to authenticate.
- If you allowed authentication from any tenant, and used the common endpoint (rather than your specific tenant ID), the user may be asked to allow your app to access their account. If they are on their home tenancy, you will have already approved this for all users.
- The user is redirected to the oauth.php file, where a background request is made back to login.microsoftonline.com to obtain a token. Once this has been successful, the user is redirected back to their original destination.
- If the user lands on index.php and their session key cookie already exists, and exists in the database, and has not expired, they will be allocated that token’s data.
- If the user lands on index.php with a session key cookie, but it is going to expire in the next 10 minutes, we will perform a refresh request in the background.
- If the user lands on index.php with a session key cookie, but it’s expired, they are redirected back to login.microsoftonline.com – which may automatically log them back in, or may prompt, depending on their settings.