themancorp
themancorp

Reputation: 1

Can I use Autodiscover with OAuth for Email Exchange integration?

I'm trying to connect up using C# to an email account using OAuth authentication. I've got that all working fine, but it doesn't seem to work once I set the AutodiscoverUrl property instead of a predefined Url on an ExchangeService object i.e.

This works:

exchangeService.Url = "***some url***";

But using this doesn't:

exchangeService.AutodiscoverUrl("[email protected]", redirectionAddress => true);

Things to note:

  1. OAuth works fine when I set the Url property directly.
  2. Autodiscover works fine when I login using basic authentication (support soon to be removed)

So how can I use both OAuth and AudodiscoverUrl at the same time? Is this even possible?

My implementation is more or less a port from this MS guide (App-only authentication section):

https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-authenticate-an-ews-application-by-using-oauth

Upvotes: 0

Views: 1112

Answers (1)

Glen Scales
Glen Scales

Reputation: 22032

If your using the Client Credentials flow (App tokens) then Autodiscover v1 won't work. If your using delegate Access then it will work okay

One workaround is to use Autodiscoverv2 (which is what the new version of Outlook uses). This is unauthenticated so will return just the EWS Endpoint eg

        string autodiscoverv2Endpoint = $"https://outlook.office365.com/autodiscover/autodiscover.json/v1.0/{emailAddress}?Protocol=EWS";
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (compatible; AcmeInc/1.0)");
            dynamic adResponse = JObject.Parse(client.GetAsync(autodiscoverv2Endpoint).GetAwaiter().GetResult().Content.ReadAsStringAsync().GetAwaiter().GetResult());
            return adResponse.Url.ToString();
        }

If you using App Tokens against Office365 the actual need for AutoDiscover is negalible as the endpoint will always be https://outlook.office365.com/ews/exchange.asmx . If you need to support Hybrid Modern Auth and your switching between OnPrem and Hybrid Mailboxes within your code then you will need to do that, but keep in mind you will also need a different access Token when accessing OnPrem Mailboxes to those in the cloud becuase the Token Audience will change.

Upvotes: 2

Related Questions