I'm following this documentation: https://docs.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code
Under, REQUEST AN AUTHORIZATION CODE, it gives a sample code involving an endpoint for OAuth 2.0
. I've followed this structure to base my own request resembling:
https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
&redirect_uri=https://example.com
&response_mode=query
&resource=6731de76-14a6-49ae-97bc-6eba6914391e
&state=12345
During my tests, I've even tried (getting the request as bare as possible):
https://login.microsoftonline.com/{tenant}/oauth2/authorize?
client_id=6731de76-14a6-49ae-97bc-6eba6914391e
&response_type=code
Here's the interesting thing: If I access these domains through the browser, they return a "successful" call, like so:
https://example.com/?code=AOA...................................
However, I can't seem to get this same result (acquire a code) through a PHP
workaround.
I've tried:
file_get_contents($my_url);
But all that returns is an error and a login page for Microsoft.
I've also tried doing so in cURL
, but no luck.
Can anyone advise on how to replicate getting such a code (automatically)?
The need here was to access APIs as a user later as well.
When you redeem an authorization code, you get an access token and a refresh token. The access token you attach to API calls, and expires in 1 hour by default. But the refresh token expires in 14 days by default, and can be used to get a new access token and refresh token. So you can have perpetual access as long as you use the refresh token to get new tokens always within 14 days.
The user's access will be checked every time you refresh, so if their account is disabled or access is removed, you will get an error instead of new tokens.
Short answer: you can't. To get an authorization code, you must redirect the browser so the user can sign in, go through MFA if necessary, sign in to their org local AD... As an end result, the user will be sent back to your app with the code, which you can then redeem for access tokens to APIs you want to call that are protected by Azure AD.
You could redirect user to microsoft login page by using header() function to send HTTP Location header:
header("Location: https://login.microsoftonline.com/xxxxxx/oauth2/authorize?client_id=xxxxxx&response_type=code&redirect_uri=http%3A%2F%2Flocalhost:8088/testauth.php%2F&response_mode=query&resource=https%3A%2F%2Fgraph.windows.net%2F&state=12345");
After user entered username/password , azure ad will redirect to redirect url with code , you could get the code by :
echo $_GET['code'];