无需登录重定向的 Office365 身份验证

Office365 authentication without login redirection

我正在尝试从 Office365 电子邮件加载数据而无需用户交互。我已经创建了 Azure App,并且拥有客户端 ID 和客户端密码。 我还有用户信息(电子邮件+密码)。

我需要调用Office365API从邮箱下载邮件。但我需要应用程序在后台下载它们而无需用户交互(重定向到 MS/Office365 登录页面)以将 authenticated/logged 放入邮箱。

有什么方法可以仅通过 Office API 执行此操作而无需重定向?

感谢您提供任何信息。

是的,您可以使用客户端凭据流程创建守护程序服务应用程序以对应用程序进行身份验证。

下面是使用 Microsoft Graph SDK 通过此流程检索邮件的代码示例:

string clientId = "";
string clientsecret = "";
string tenant = "";
string resourceURL = "https://graph.microsoft.com";
string authority = "https://login.microsoftonline.com/" + tenant + "/oauth2/token";
string userMail = "user1@yourdomain.onmicrosoft.com";

var credential = new ClientCredential(clientId, clientsecret);
AuthenticationContext authContext =new AuthenticationContext(authority);
var authResult = await authContext.AcquireTokenAsync(resourceURL, credential);
var graphserviceClient = new GraphServiceClient(
new DelegateAuthenticationProvider(
   (requestMessage) =>
   {
       requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);

       return Task.FromResult(0);
   }));

var items = await graphserviceClient.Users[userMail].Messages.Request().OrderBy("receivedDateTime desc").GetAsync();

foreach (var item in items)
{
        Console.WriteLine(item.Subject);
}

并且我们需要在 Azure AD 门户上注册应用程序并授予应用程序 Mail.Read 范围,如下图所示:

有关在服务或守护程序应用程序中调用 Microsoft Graph 的更多详细信息,请参阅 here