skip to Main Content

We have an application coded on PHP to grab inbox emails from an email id, which was working fine. this was a basic authentication application. Recently they have stopped basic authentication, so we created an account on Azure to get a new authentication and based on that we want to grab emails.

We have created a code using the app id and secret id.
When we open the page, it will redirect to the login page, that’s the issue.
We need it should be automatically log in and grab the emails.
This is a cron process, so every time we need to enter login, grabbing emails is not a solution.

https://xxxx.co/projects/test.php?action=login
When we open this link, it will ask for login. We dont want that, because we already put every data like app id, secret id and tenant id.

If we are already logged in microsoft then it will not ask for login, will got through the email grab page. But when we open on incognito, its asking for login. How can we remove that and grab emails directly

<?php


$appid = "xxxxx";

$tennantid = "xxxxx";

$secret = "xxxxxx";

$login_url ="https://login.microsoftonline.com/".$tennantid."/oauth2/v2.0/authorize";


session_start ();

$_SESSION['state']=session_id();

echo "<h1>MS OAuth2.0 Demo </h1><br>";


if (isset ($_SESSION['msatg'])){

   echo "<h2>Authenticated ".$_SESSION["uname"]." </h2><br> ";

   echo '<p><a href="?action=logout">Log Out</a></p>';

} //end if session

else   echo '<h2><p>You can <a href="?action=login">Log In</a> with Microsoft</p></h2>';


if ($_GET['action'] == 'login'){

   $params = array ('client_id' =>$appid,

      'redirect_uri' =>'https://xxx.co/projects/test.php',

      'response_type' =>'token',

      'scope' =>'https://graph.microsoft.com/User.Read',

      'state' =>$_SESSION['state']);

   header ('Location: '.$login_url.'?'.http_build_query ($params));

}


echo '

<script> url = window.location.href;

i=url.indexOf("#");

if(i>0) {

 url=url.replace("#","?");

 window.location.href=url;}

</script>

';


if (array_key_exists ('access_token', $_GET))

 {

   $_SESSION['t'] = $_GET['access_token'];

   $t = $_SESSION['t'];

$ch = curl_init ();

curl_setopt ($ch, CURLOPT_HTTPHEADER, array ('Authorization: Bearer '.$t,

                                            'Conent-type: application/json'));

curl_setopt ($ch, CURLOPT_URL, "https://graph.microsoft.com/v1.0/me/");

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);

$rez = json_decode (curl_exec ($ch), 1);

if (array_key_exists ('error', $rez)){  

 var_dump ($rez['error']);    

 die();

}

else  {

$_SESSION['msatg'] = 1;  //auth and verified

$_SESSION['uname'] = $rez["displayName"];

$_SESSION['id'] = $rez["id"];


}

curl_close ($ch);

   header ('Location: https://xxxx.co/projects/test.php');

}


if ($_GET['action'] == 'logout'){

   unset ($_SESSION['msatg']);

   header ('Location: https://xxxx.co/projects/test.php');

}

When we open this code, it will ask for login. We dont want that. It will directly grab emails using php

2

Answers


  1. Chosen as BEST ANSWER

    <?php
    
    $tenantId = 'xxxx';
    $client_id = 'aaaaa;
    $client_secret = 'bbb';
    $resource = 'https://graph.microsoft.com';
    $tokenEndpoint = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token';
    
    $data = array(
        'grant_type' => 'client_credentials',
        'client_id' => $client_id,
        'client_secret' => $client_secret,
        'resource' => $resource
    );
    
    $ch = curl_init($tokenEndpoint);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $result = curl_exec($ch);
    curl_close($ch);
    
    $token = json_decode($result)->access_token;
    
    
    
    // print_r($token);
    
    
    
    $graphApiEndpoint = 'https://graph.microsoft.com/v1.0/me';
    
    $ch = curl_init($graphApiEndpoint);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        "Authorization: Bearer $token",
        "Content-type: application/json"
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    
    $result = curl_exec($ch);
    curl_close($ch);
    
    $response = json_decode($result);
    
    
    print_r($response);
    if ($response && isset($response->value)) {
        $messages = $response->value;
    } else {
        // Error handling if the response is not as expected
        if ($result === false) {
            echo 'cURL error: ' . curl_error($ch);
        } else {
            echo 'Invalid response format.';
        }
        
        // Additional error handling steps if required
        // ...
    }
    
    ?>
    
    ?>

    COde is working till the token generation, after that we tried to fetch /me its getting error.


  2. To fetch emails using Azure authentication and PHP coding, you need to use the Microsoft Graph API.

    Use OAuth 2.0 authorization to authenticate the user and obtain an access token. And use it to call the Microsoft Graph API to retrieve the user’s emails.

    And for your issue, it is possible for the login page to appear when you are not logged in. To overcome this, you need to use OAuth 2.0 client credentials instead of authorization code.

    Sample code to use the client credentials to fetch an access token.

    $tenantId = 'your-tenant-id';
    $client_id = 'your-client-id';
    $client_secret = 'your-client-secret';
    $resource = 'https://graph.microsoft.com';
    $tokenEndpoint = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token';
    
    $data = array(
        'grant_type' => 'client_credentials',
        'client_id' => $client_id,
        'client_secret' => $client_secret,
        'resource' => $resource
    );
    
    $options = array(
        'http' => array(
            'header' => "Content-type: application/x-www-form-urlencodedrn",
            'method' => 'POST',
            'content' => http_build_query($data)
        )
    );
    
    $context = stream_context_create($options);
    $result = file_get_contents($tokenEndpoint, false, $context);
    $token = json_decode($result)->access_token;
    
    

    After fetching the access token, you can use it for calling the Microsoft Graph API and retrieve the user’s emails.

    Sample code to retrieve the user’s emails.

    php
    $graphApiEndpoint = 'https://graph.microsoft.com/v1.0/me/messages';
    $options = array(
        'http' => array(
            'header' => "Authorization: Bearer $tokenrn" .
                        "Content-type: application/jsonrn",
            'method' => 'GET'
        )
    );
    
    $context = stream_context_create($options);
    $result = file_get_contents($graphApiEndpoint, false, $context);
    $messages = json_decode($result)->value;
    
    

    For more information refer to the MSDoc1 and MSDoc2.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search