没有登录重定向的Office365身份验证

时间:2016-07-14 09:58:44

标签: authentication office365 azure-active-directory office365api office365-apps

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

我需要调用Office365 API来从邮箱下载电子邮件。但我需要应用程序在后台下载它们而无需用户交互(重定向到MS / Office365登录页面)以获得身份验证/登录到邮箱。

有没有办法只通过Office API如何做到这一点,而不需要重定向?

感谢您的任何信息。

1 个答案:

答案 0 :(得分:2)

是的,您可以使用客户端凭据流创建一个守护程序服务应用程序来验证该应用程序。

以下是使用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 范围,如下图所示: enter image description here

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