简体   繁体   中英

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, "mailbox@user.com"),
            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?

Check the token your using in

Credentials = new OAuthCredentials(authResult.AccessToken),

in jwt.io

What you should see in the roles is

在此处输入图像描述

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM