EWS OAuth Authentication

0 votes
asked Oct 25 by shaapala (170 points)

I am able to get a token fine but when I go to Login I'm getting this error:
Rebex.Net.EwsException: 'Internal server error. ExchangeImpersonation SOAP header must be present for this type of OAuth token.

Doing some googling it seems I need to add the "X-AnchorMailbox" header.
But when I try to use ews.ProvisionHeaders I'm not sure what format I'm supposed to put the string in to achieve adding this header to the login request.
I've tried var headers = new List() { "X-AnchorMailbox, yyy@example.com" };
But the login fails with Rebex.Net.EwsException: 'Authentication required.' when I do that.
Any idea how to get this to work? What am I doing wrong?

Here is my sample code:

app = ConfidentialClientApplicationBuilder.Create(clientId)
            .WithClientSecret(secret)
            .WithAuthority(new Uri("https://login.microsoftonline.com/<tenentidgoeshere>"))
            .Build();
        var result = app.AcquireTokenForClient(scopes)
            .ExecuteAsync().Result;



        var ews = new Rebex.Net.Ews();
        ews.Connect("outlook.office365.com");
        var headers = new List<string>() { "X-AnchorMailbox, yyy@example.com" };
        ews.ProvisionHeaders(headers.ToArray());
        ews.Login(result.AccessToken, EwsAuthentication.OAuth20);
Applies to: Rebex Secure Mail

1 Answer

0 votes
answered Oct 25 by Pavel Matyska (12,040 points)
selected Oct 25 by shaapala
 
Best answer

Hello,

instead of filling your email address into an HTTP header, please try setting it into an SOAP impersonation header as the first error message said. To do that please use these lines of code before calling ews.Login(...) method.

ews.Settings.Impersonation = new EwsImpersonation();
ews.Settings.Impersonation.SmtpAddress = "yyy@example.com";

Just a note, your second error is most likely thrown from ews.ProvisionHeaders(...) method, not the ews.Login(...) method.

commented Oct 25 by shaapala (170 points)
Thank you! that did the trick!
...