Skip to content

Instantly share code, notes, and snippets.

@gscales
Last active November 23, 2020 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gscales/a946025d143436ec64a8cc4cb27693c0 to your computer and use it in GitHub Desktop.
Save gscales/a946025d143436ec64a8cc4cb27693c0 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading.Tasks;
using System.Net.Http;
using Microsoft.Identity.Client;
using Newtonsoft.Json;
using EWSWSDLoAuthExample.com.office365.outlook;
namespace EWSWSDLoAuthExample
{
class Program
{
static void Main(string[] args)
{
OAuthExchangeServiceBinding exchangeServiceBinding = new OAuthExchangeServiceBinding();
String ClientId = "111111-52b3-4102-aeff-aad2292ab01c";
String MailboxName = "user@domain.onmicrosoft.com";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (compatible; AcmeInc/1.0)");
StringContent RealmRequest = new StringContent("{\"username\":\"" + MailboxName + "\"}");
String DiscoveryURL = "https://login.microsoftonline.com/common/GetCredentialType";
dynamic RealmDiscover = JsonConvert.DeserializeObject(httpClient.PostAsync(DiscoveryURL, RealmRequest).Result.Content.ReadAsStringAsync().Result);
if ((Int32)RealmDiscover.EstsProperties.DomainType == 1 || (Int32)RealmDiscover.EstsProperties.DomainType == 2)
{
exchangeServiceBinding.Credentials = new NetworkCredential("user1@contoso.com", "password");
exchangeServiceBinding.RequestServerVersionValue = new RequestServerVersion();
exchangeServiceBinding.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2010_SP2;
}
else
{
String AutoDiscoverEndpoint = $"https://outlook.office365.com/autodiscover/autodiscover.json/v1.0/{MailboxName}?Protocol=EWS";
dynamic JsonResult = JsonConvert.DeserializeObject(httpClient.GetAsync(AutoDiscoverEndpoint).Result.Content.ReadAsStringAsync().Result);
if (IsPropertyExist(JsonResult, "Url"))
{
String AudienceHostName = new Uri(JsonResult.Url.ToString()).Host;
string scope = "https://" + AudienceHostName + "/EWS.AccessAsUser.All";
PublicClientApplicationBuilder pcaConfig = PublicClientApplicationBuilder.Create(ClientId).WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs);
exchangeServiceBinding.PublicClientApplication = pcaConfig.Build();
exchangeServiceBinding.oAuthScopes = new[] { scope };
exchangeServiceBinding.AnchorMailbox = MailboxName;
var IntToken = exchangeServiceBinding.PublicClientApplication.AcquireTokenInteractive(exchangeServiceBinding.oAuthScopes).ExecuteAsync().Result;
exchangeServiceBinding.LogonHint = IntToken.Account.Username;
exchangeServiceBinding.Url = JsonResult.Url.ToString();
exchangeServiceBinding.RequestServerVersionValue = new RequestServerVersion();
exchangeServiceBinding.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2016;
}
}
GetMailTipsType GetMailTips = new GetMailTipsType();
GetMailTips.MailTipsRequested = new MailTipTypes();
GetMailTips.MailTipsRequested = MailTipTypes.OutOfOfficeMessage;
GetMailTips.Recipients = new EmailAddressType[1];
GetMailTips.Recipients[0] = new EmailAddressType();
GetMailTips.Recipients[0].EmailAddress = MailboxName;
GetMailTips.SendingAs = new EmailAddressType();
GetMailTips.SendingAs.EmailAddress = MailboxName;
GetMailTipsResponseMessageType GetMailTipsResponse = null;
try
{
GetMailTipsResponse = exchangeServiceBinding.GetMailTips(GetMailTips);
Console.WriteLine("OOFTip" + GetMailTipsResponse.ResponseMessages[0].MailTips.OutOfOffice.ReplyBody.Message);
}
catch (Exception Exception)
{
//To Do
}
}
public static bool IsPropertyExist(dynamic settings, string name)
{
if (settings is Newtonsoft.Json.Linq.JObject)
return ((Newtonsoft.Json.Linq.JObject)settings).ContainsKey(name);
return settings.GetType().GetProperty(name) != null;
}
}
class OAuthExchangeServiceBinding : ExchangeServiceBinding
{
public String AnchorMailbox { get; set; }
public IPublicClientApplication PublicClientApplication { get; set; }
public String[] oAuthScopes { get; set; }
public String LogonHint { get; set; }
protected override System.Net.WebResponse GetWebResponse(System.Net.WebRequest request)
{
if (!String.IsNullOrEmpty(AnchorMailbox))
{
request.Headers.Add("X-AnchorMailbox", AnchorMailbox);
}
if (PublicClientApplication != null)
{
Task<AuthenticationResult> authtask = null;
request.Headers.Remove("Authorization");
try
{
authtask = Task.Run<AuthenticationResult>(async () => await PublicClientApplication.AcquireTokenSilent(oAuthScopes, LogonHint).ExecuteAsync());
}
catch (MsalUiRequiredException)
{
authtask = Task.Run<AuthenticationResult>(async () => await PublicClientApplication.AcquireTokenInteractive(oAuthScopes).ExecuteAsync());
}
request.Headers.Add("Authorization", "Bearer " + authtask.Result.AccessToken);
}
System.Net.HttpWebResponse
response = (System.Net.HttpWebResponse)base.GetWebResponse(request);
return response;
}
}
}
@ananimesh
Copy link

We have EWS proxy in our code and trying to use your suggestion to use modern authentication.
When I am trying to use a token generated from a registered app. However, I get the exception,"ExchangeImpersonation SOAP header must be present for this type of OAuth token." in GetWebResponse.
Can you please suggest what I should do?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment