Microsoft Graph ASP.NET MVC 5发送邮件引发未知错误

时间:2018-07-20 15:59:21

标签: c# asp.net-mvc microsoft-graph

曾致力于与MS Graph API交互的ASP.NET MVC 5应用程序。

控制器为当前用户获取一个图形客户端,然后使用该客户端发送电子邮件。

public class EmailController : Controller
{
    // GET: Email
    public async Task<ActionResult> Index()
    {
        var client = await MSGraphServiceClient.GetGraphServiceClientAsync();
        await InvitationHelper.SendEmail(client);


        return Content("");
    }
}

public static async Task<GraphServiceClient> GetGraphServiceClientAsync()
    {
        string appId = ConfigurationManager.AppSettings["ida:ClientId"];
        string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
        string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
        // Get Signed in user
        string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
        // Get app and user id claims from Azure
        string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
        string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
        // Specify Graph resource URL
        string graphResourceID = "https://graph.microsoft.com";

        // get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
        ClientCredential clientcred = new ClientCredential(appId, appKey);
        // initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's database
        AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID, new ADALTokenCache(signedInUserID));
        AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));

        // use delegate to create auth provider using async auth result
        var delegateAuthProvider = new DelegateAuthenticationProvider((requestMessage) =>
        {
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authenticationResult.AccessToken);
            return Task.FromResult(0);
        });

        // return the graph service client
        return new GraphServiceClient(delegateAuthProvider);
    }

    public static async Task<bool> SendEmail(GraphServiceClient graphServiceClient)
    {

            var message = new Message()
            {
                Subject = "Test",
                Body = new ItemBody()
                {
                    ContentType = BodyType.Text,
                    Content = "This is a test"
                },
                ToRecipients = new List<Recipient>() { new Recipient() { EmailAddress = new EmailAddress() { Address = "jonathan.sweetland@gmail.com" } } }
            };
            var request = graphServiceClient.Me.SendMail(message, true).Request();
            await request.PostAsync();

            return true;
}

这不是权限错误,因为在AAD上,我已经授予了此应用的所有权限。我还有其他图形调用正在工作,所以我知道它可以使用相同的代码正确进行身份验证。

Error

Stack trace

1 个答案:

答案 0 :(得分:0)

按照建议的方式使用了提琴手,并且JSON响应与显示的错误消息相同。

经过大量的试验,我发现如果您尝试在未通过Outlook帐户设置的Azure Active Directory租户进行身份验证的同时,在Graph API上使用SendMail。即使该帐户在其他租户上有一个Outlook帐户,您也将无法使用SendMail终结点。