How can I access another user's resources (specifically emails) using Microsoft Graph in an MVC app?

Lucien P

I seem to be having issues giving my application the permissions required to access another user in the oranization's email messages. I had my admin grant my application all of the possible permissions through the Azure Portal and I’m getting an ‘Access is Denied’ error in the test application I downloaded from the Graph website. This makes me think that perhaps I am not using the correct call to the API.

Here is the code I’m using to retrieve another user’s email:

IMailFolderMessagesCollectionPage messages = await graphClient.Users["userID"].MailFolders.Inbox.Messages.Request().Top(25).GetAsync();

where “userID” is the id value I obtained from getting all users in my organization through the graph explorer.

Full code:

(Controller)

[Authorize]
public async Task<ActionResult> GetEmails()
        {
        try
        {
            // Initialize the GraphServiceClient.
            GraphServiceClient graphClient = SDKHelper.GetAuthenticatedClient();

            ResultsViewModel results = new ResultsViewModel();
            // Get the messages. 
            results.Items = await graphService.GetMyInboxMessages(graphClient);
            return View("Graph", results);
        }
        catch (ServiceException se)
        {
            if (se.Error.Code == Resource.Error_AuthChallengeNeeded) return new EmptyResult();
            return RedirectToAction("Index", "Error", new { message = Resource.Error_Message + Request.RawUrl + ": " + se.Error.Message });
        }
    }

(graphService.cs)

public async Task<List<ResultsItem>> GetMyInboxMessages(GraphServiceClient graphClient)
    {
        List<ResultsItem> items = new List<ResultsItem>();

        // Get messages in the Inbox folder. 
        //IMailFolderMessagesCollectionPage messages = await graphClient.Me.MailFolders.Inbox.Messages.Request().GetAsync();  
        IMailFolderMessagesCollectionPage messages = await graphClient.Users["e87151ce-093b-4820-a98c-4cef247ed2be"].MailFolders.Inbox.Messages.Request().Top(25).GetAsync();

        string recipients = string.Empty;
        if (messages?.Count > 0)
        {
            foreach (Message message in messages)
            {
                //foreach (Recipient recipient in message.ToRecipients)                    
                for (int i = 0; i < message.ToRecipients.Count(); i++)
                    recipients += ((i != 0 ? "; " : "") + message.ToRecipients.ElementAt(i).EmailAddress.Address.ToString());

                items.Add(new ResultsItem
                {
                    Type = "message",
                    SentDateTime = message.SentDateTime.Value.DateTime.ToLocalTime(),
                    Subject = message.Subject,
                    From = message.From.EmailAddress.Address.ToString(),
                    To = recipients,
                    Id = message.Id,
                    Body = message.Body.Content.ToString()
                });
            }
        }
        return items;
    }

Is this an incorrect GET request? Or is it a permissions issue?

Thanks in advance for your help.

Nan Yu

You could request app only token (client credential flow) using Read mail in all mailboxes application permissions for access to the Microsoft Graph. According to your description , you register application in azure portal (azure ad v1.0) , you could try below steps:

  1. set Read mail in all mailboxes application permissions for microsoft graph api : enter image description here

  2. ask your admin to grant permissions (do admin consent for application permission)for all accounts in current directory by clicking Grant Permissions button as shown in above screenshot .

  3. Use client credential flow to acquire app only token using ADAL library : AzureAuthenticationProvider .cs :

    public class AzureAuthenticationProvider : IAuthenticationProvider
    {
        private string _azureDomain = "xxxx.onmicrosoft.com";
    
        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
          try
          {
            string clientId = "xxxxx-xxxx-xxxx-xxxx-xxxxxxxx";
            string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
    
            AuthenticationContext authContext = new AuthenticationContext("https://login.windows.net/" + _azureDomain + "/oauth2/token");
    
            ClientCredential credentials = new ClientCredential(clientId, clientSecret);
    
            AuthenticationResult authResult = await authContext.AcquireTokenAsync("https://graph.microsoft.com/", credentials);
    
            request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
          }
          catch (Exception ex)
          {
          }
        }
    }
    

    if you decode your token , you will find Mail.Read app permission in roles claim .

  4. Then you could use Microsoft graph client library to get mails of users :

        GraphServiceClient graphClient = new GraphServiceClient(new AzureAuthenticationProvider());
    
        //List<ResultsItem> items = new List<ResultsItem>();           
        IMailFolderMessagesCollectionPage messages = await graphClient.Users["77cac441-8279-452e-8904-ff24ddf5c715"].MailFolders.Inbox.Messages.Request().Top(25).GetAsync();
    
  5. The result : enter image description here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Restrict Microsoft app access to MS Graph emails for a single user

Access Microsoft Graph resources with an App access token (no user sign-in)

Microsoft-Graph - As an Azure AD Admin how you can get a valid access_token for another user

How can I access Azure Graph AND Microsoft Graph using same OAuth2 token?

How can I insert into a table both a select max function from another table and variables input by the user, using PHP, SQL and Microsoft Access?

How can I get the unread emails using Graph

How do I only allow authenticated user (using cognito) access to their own S3 bucket/key specifically?

How to access Microsoft Graph's services with service-user credentials

How to retrieve all uncategorized emails count in office 365 user mailboxes using Microsoft graph api

How to set the access token lifetime for an app using the Microsoft Graph API

Using Microsoft Graph to fetch emails without any user interaction

How do I list emails with attachment names using Microsoft Graph SDK?

c# - how can I access an `Microsoft.AspNetCore.Authorization` authorised user's details

How do I get the user's email when using Microsoft Account Authentication in an MVC project?

In Terraform, how can I use another deployment's resources?

How can I make another user an administrator on the Microsoft Surface?

How can I access a user's openId/OAuth avatar and email address in MVC5?

Microsoft graph - listing emails - Access to OData is disabled

microsoft graph get access token that can be use to get user's calender

How can I give access of var/www/html to another user using AWS?

How do I access another user's registry hive using Powershell?

How to retrieve the user's profile and the user's calendars using the Microsoft Graph API?

How can I get a list of AD user groups along with AD user with Microsoft Graph SDK

How can I get access to user folder from another computer?

using Facebook Graph API how can i access friends names

How to retrieve another user's MS Teams chats with the Microsoft Graph API?

How do I Call Microsoft Teams OnlineMeeting endpoints via Microsoft Graph API using a console app?

How can I test that a user can't access a page with access reserved to another user?

How do I access another user's data by a specific field?