Microsoft Graph: User Authentication with PHP (WebApp)

First you need to: 1. Register your application, 2. Set the callback URL redirect. 3. Create a client secret key.

state (recomended): A value included in the request that’s also returned in the token response. It can be a string of any content that you wish. A randomly generated unique value is typically used for preventing cross-site request forgery attacks. This property is also used to encode information about the user’s state in the app before the authentication request occurred, such as the page or view they were on.

Then make a call to /authorize endpoint. Click here for reference.

<a href="https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/authorize?
         client_id={client-id}
         &response_type=code
         &redirect_uri=http://localhost:8000/callback
         &response_mode=query
         &scope=User.Read Mail.Read
         &state=12345">Sign-in</a>

After the sign-in, you will get a request to the callback URL. Click here for reference.

GET https://localhost:8000/callback?
	code=M0ab92efe-b6fd-df08-87dc-2c6500a7f84d
    &state=12345
    &session_state=fe1540c3-a69a-469a-9fa3-8a2470936421#

Then we need to create PHP file file to handle /callback route. Click here for reference.

Route::get('/callback', function (Request $request) {

    $res = Http::asForm()->post('https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token', [
        'grant_type' => 'authorization_code',
        'client_id' => '{client-id}',
        'code' => $request->input('code'),
        'scope' => 'Mail.Read User.Read',
        'redirect_uri' => 'http://localhost:8000/callback',
        'client_secret' => '{client-secret}'
    ]);
  
    dump($res->body());
});

Then you will get JSON with your access token. Click here for the reference.

Note: A refresh_token will only be returned if offline_access was included as a scope parameter.

{
    "token_type": "Bearer",
    "scope": "Mail.Read User.Read",
    "expires_in": 3736,
    "ext_expires_in": 3736,
    "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6Ik5HVEZ2ZEstZnl0aEV1Q...",
    "refresh_token": "AwABAAAAvPM1KaPlrEqdFSBzjqfTGAMxZGUTdM0t4B4..."
}

Once you get the access_token, you can call the Microsoft Graph API.

GET https://graph.microsoft.com/v1.0/me HTTP/1.1
Authorization: Bearer {access_token}
Host: graph.microsoft.com

References: