I am new to Microsoft Graph and I want to use it to read and move email messages. This is my C# code:
static async Task Main(string[] args)
{
var scopes = new[] { "https://graph.microsoft.com/.default" }
var tenantId = args[0];
var clientId = args[1];
var clientSecret = args[2];
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
}
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret, options)
var graphClient = new GraphServiceClient(clientSecretCredential, scopes)
var messsages = await graphClient.Me.Messages.GetAsync();
Console.WriteLine(messsages.Value.Count);
Console.WriteLine("Hello, World!");
}
This is the error message I got:
C:UsersdaansourcenonreposTryMicrosoftGraphTryOtherProgram.cs(26,31): warning CS8602: Dereference of a possibly
null reference. [C:UsersdaansourcenonreposTryMicrosoftGraphTryOtherTryOther.csproj] C:UsersdaansourcenonreposTryMicrosoftGraphTryOtherProgram.cs(26,31): warning CS8602: Dereference of a possibly
null reference. [C:UsersdaansourcenonreposTryMicrosoftGraphTryOtherTryOther.csproj] Unhandled exception. Microsoft.Graph.Models.ODataErrors.ODataError: /me request is only valid with delegated authentication flow.
so the message is:
/me request is only valid with delegated authentication flow.
I am not sure what to do now. Do I really need a "delegated authentication flow". Or is there an easier way to access my messages?
I’ve seen such errors before on stackoverflow but such posts do not explain how I resolve it in a way it gives me access to the emails.
2
Answers
Your application is a confidential application that requests a token through the client credential flow. This is why the /me path is not functioning as mentioned in the error notification.
Essentially, you still have access to messages from any user within your organization/tenant, but you need to construct a different URL to retrieve those messages.
For instance, you could use this URL to retrieve messages for a user:
Another interesting requests that might help you:
I agree with @MartinGodzina, you need to use
/users
endpoint with client credentials flow as/me
endpoint works only with delegated flows like auth code or interactive.I registered one Azure AD application and granted API permissions of Application type as below:
Now, you can make use of below modified code by passing either
userID
oruserUPN
to read messages using client credentials flow:Response:
Reference:
List messages – Microsoft Graph v1.0