Why am I getting an Unauthorized response with the Outlook API with Azure Active Directory?

christian. igay 1 Reputation point
2020-11-28T09:18:38.82+00:00

I'm creating a task that will retrieve the messages in outlook mail with Microsoft Azure Active Directory.

I setup my azure account. Register an app, add certificate then add user to my AD. My signin method returns an access token which means signin is successful and pass the access token to outlook messages API. but the Outlook messages API returns unauthorize.

Here is my scope: email Group.Read.All Mail.Read Mail.Read.Shared Mail.ReadBasic openid profile User.Read User.ReadBasic.All Mail.ReadWrite

I used Laravel HTTP Client to send request. Hope anyone can help me, Im stuck on this problem for week

Here my code:

 public function __construct()
 {
      $this->params = [
         'client_id'       => env('OAUTH_APP_ID'),
         'scope'           => env('OAUTH_SCOPES'),
         'client_secret'   => env('OAUTH_APP_PASSWORD'),
         'username'        => 'xxxxxxxx@mytenant.onmicrosoft.com',
         'password'        => 'xxxxxxxx',
         'grant_type'      => 'password',
         'redirectUri'     => env('OAUTH_REDIRECT_URI'),
         'urlAuthorize'    => env('OAUTH_AUTHORITY').env('OAUTH_AUTHORIZE_ENDPOINT'),
         'urlAccessToken'  => env('OAUTH_AUTHORITY').env('OAUTH_TOKEN_ENDPOINT'),
         'urlResourceOwnerDetails' => '',
      ];
  }
  public function signin()
  {
      $url = 'https://login.microsoftonline.com/organizations/oauth2/v2.0/token';
      $response = Http::asForm()->post($url, $this->params);
      if($response->ok()){
           $returnData = $response->json();
           $mail_api = 'https://outlook.office.com/api/v2.0/me/messages';
           $messagesResponse = Http::withToken($returnData['access_token'])->get($mail_api);
           dd($messagesResponse);
      }
   }
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,592 questions
Microsoft Entra ID
Microsoft Entra ID
A Microsoft Entra identity service that provides identity management and access control capabilities. Replaces Azure Active Directory.
19,473 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. 2020-11-30T17:34:49.593+00:00

    Hello @christian. igay , Mail.Read is good enough. Please try with https://graph.microsoft.com/v1.0/me/messages which is the recommend API to access Outlook features.

    Please let me know if you need more help. If the answer was helpful to you, please accept it and optionally fill the feedback form it so that other members in the community can benefit from it.

    0 comments No comments