How get the messages from user's mailbox on Exchange on-prem which enabled Hybrid Modern Authentication using oauth

Dung Lee 0 Reputation points
2023-06-16T02:32:09.4966667+00:00

My target is get message from mailbox's user on Exchange on-prem using modern auth. It's coded by .Net framework.

I don't care we need to use ADFS or not. We can use any library/packages to support. We also enabled Hybrid Modern Auth. So we can use access token got from the application which created on Azure....

On Hybrid Modern Auth, I tried to use the access token got from the app on Azure Active Directory like this:

public static async Task<string> GetAccessTokenAsync()        
{                       
	string clientId = "8bf6e5f1-e994-4f29-b888-0456b8942***";            
	string secret = "6SF8Q~w.7LQgIYFyKSFdk4pXjCnbNnc1K5Jp****"; 
	string msDomain = "domain.onmicrosoft.com"; 
	
	IConfidentialClientApplication thisApp = 	ConfidentialClientApplicationBuilder.Create(clientId)                
	.WithClientSecret(secret)                               
	.WithAuthority($"https://login.windows.net/{msDomain}/")                
	.Build();           
AuthenticationResult accessToken = await thisApp.AcquireTokenForClient(new[] { $"https://outlook.office365.com/.default" }).ExecuteAsync();  

	return accessToken.AccessToken;       
 
}

Then use above access token to auth Exchange on-prem but got error "401 un-auth"

var accessToken = GetAccessTokenAsync().Result;
 ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
 service.Url = new Uri("https://domain.com/EWS/Exchange.asmx"
service.Credentials = new OAuthCredentials(accessToken);
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "******@domain.com");
Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);

Do you guys have any ideas?

Exchange Online
Exchange Online
A Microsoft email and calendaring hosted service.
6,178 questions
Exchange | Exchange Server | Other
Exchange | Hybrid management
Developer technologies | C#
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.