Search code examples
oauthoffice365exchange-serverexchangewebservicesimpersonation

How do I access Outlook365 mailbox using impersonation using .NET?


I'm using this code:

        var cca = ConfidentialClientApplicationBuilder
            .Create(clientId)
            .WithClientSecret(clientSecret)
            .WithTenantId(tenantId)
            .Build();

        var ewsScopes = new [] { "https://outlook.office365.com/.default" };
        var authResult = await cca.AcquireTokenForClient(ewsScopes).ExecuteAsync(cancellationToken);

        var service = new ExchangeService
        {
            Credentials = new OAuthCredentials(authResult.AccessToken),
            Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx"),
            ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "[email protected]"),
            TraceListener = new TraceListener(),
            TraceEnabled = true,
            TraceFlags = TraceFlags.All
        };

        Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);

The code throws a ServiceRequestException (403) on the last line, and trace logs contains the error:

x-ms-diagnostics: 2000008;reason="The token contains not enough scope to make this call.";error_category="invalid_grant"

Do I need to expand the ewsScopes? Or is this because I'm lacking the correct permissions in Azure? Which roles/permissions do I need?


Solution

  • Check the token your using in

    Credentials = new OAuthCredentials(authResult.AccessToken),

    in jwt.io

    What you should see in the roles is

    enter image description here

    If you don't have that role it means your application registration isn't correct (eg you have added the delegate permission instead of Application permission which is a common mistake).