I am trying to send emails from my angularjs application using MSAL setup, getting these exceptions:
Exception thrown: 'System.Net.WebException' in mscorlib.dll Exception thrown: 'Microsoft.Identity.Client.MsalServiceException' in Microsoft.Identity.Client.dll Exception thrown: 'Azure.Identity.AuthenticationFailedException' in Azure.Identity.dll
I am trying to send emails from my angularjs application using MSAL setup, got the access tokens with scopes including mail.send, then I am sending the accesstoken to ASP.NET to configure with graphclient using OnBehalfOfCredential. but getting exceptions.
msalServiceFactory.getEmailToken = function () {
const account = msalInstance.getAllAccounts()[0];
const emailScopes = ["Mail.Send"];
const silentRequest = {
scopes: emailScopes,
account: account
};
return msalInstance.acquireTokenSilent(silentRequest).then(response => {
console.log("Token acquired silently", response.accessToken);
return response.accessToken;
}).catch(error => {
console.error("Silent token acquisition failed", error);
if (error instanceof msal.InteractionRequiredAuthError) {
return msalInstance.acquireTokenPopup({ scopes: emailScopes }).then(response => {
console.log("Token acquired via popup", response.accessToken);
return response.accessToken;
}).catch(innerError => {
console.error("Interactive token acquisition failed", innerError);
return null;
});
} else {
return null;
}
});
}
return msalServiceFactory;
private void GraphServiceClient(string accessToken)
{
try
{
var scopes = new[] { "https://graph.microsoft.com/.default" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = _graphTenanatId;
// Values from app registration
var clientId = _graphClientId;
var clientSecret = _graphClientSecret;
// using Azure.Identity;
var options = new OnBehalfOfCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
};
// This is the incoming token to exchange using on-behalf-of flow
var oboToken = accessToken;
var onBehalfOfCredential = new OnBehalfOfCredential(
tenantId, clientId, clientSecret, oboToken, options);
_graphServiceClient = new GraphServiceClient(onBehalfOfCredential, scopes);
if (_graphServiceClient == null)
{
throw new InvalidOperationException("Failed to initialize GraphServiceClient.");
}
}
catch (MsalUiRequiredException msalEx)
{
LogRepository.LogMessage(this.GetType().FullName + ": MSAL UI required exception in InitGraphServiceClient: " + msalEx.ToString());
throw;
}
catch (Exception ex)
{
LogRepository.LogMessage(this.GetType().FullName + ": An error occurred in InitGraphServiceClient: " + ex.ToString());
throw;
}
} and sending email like this // Send mail as the authenticated user
await _graphServiceClient.Me.SendMail.PostAsync(sendMailBody);