Hi,
I’m trying to migrate from basic authentication to OAuth2 authentication to read email from different users from Office 365, as basic authentication will be deprecated in October.
This is the code (which is pretty straightforward):
static void Run()
{
new Aspose.Email.License()
.SetLicense("Aspose.Total.lic");
var scopes = new string[]
{
"https://outlook.office.com/.default"
};
var app = ConfidentialClientApplicationBuilder
.Create(CLIENT_ID)
.WithAuthority(AzureCloudInstance.AzurePublic, TENANT_ID)
.WithClientSecret(SECRET)
.Build();
var tokenProvider = new TokenProvider(app, scopes);
var credentials = new OAuthNetworkCredential(tokenProvider);
var client = EWSClient.GetEWSClient(
"https://outlook.office365.com/EWS/Exchange.asmx",
credentials);
}
public class TokenProvider : ITokenProvider
{
private readonly IConfidentialClientApplication _App;
private readonly string[] _Scopes;
public TokenProvider(IConfidentialClientApplication app, params string[] scopes)
{
_App = app;
_Scopes = scopes;
}
public OAuthToken GetAccessToken()
{
return GetOAuthToken();
}
public OAuthToken GetAccessToken(bool ignoreExistingToken)
{
return GetOAuthToken();
}
private OAuthToken GetOAuthToken()
{
var token = _App
.AcquireTokenForClient(_Scopes)
.ExecuteAsync()
.Result;
return new OAuthToken(
token.AccessToken,
TokenType.AccessToken,
token.ExpiresOn.DateTime);
}
public void Dispose()
{
}
}
When executing this code it results in an exception: “ExchangeImpersonation SOAP header must be present for this type of OAuth token.”.
Using Microsoft.Exchange.WebServices.Data.ExchangeService I’m able to access user mailboxes by applying an ImpersonatedUserId:
var client = new ExchangeService();
client.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
client.Credentials = new OAuthCredentials(tokenProvider.GetAccessToken().Token);
client.ImpersonatedUserId = new ImpersonatedUserId(
ConnectingIdType.SmtpAddress,
user);
client.HttpHeaders.Add("X-AnchorMailbox", user);
var folders = client.FindFolders(WellKnownFolderName.MsgFolderRoot, new FolderView(int.MaxValue));
As of this the problem is not related to the access token but to EWSClient. Could you please take a look whether I add something to my code or whether you have to update something?
I’ve already read https://forum.aspose.com/t/oauth2-support-for-o365/205188, but this is not a solution!
Regards, Stefan