Office365 authentication without login redirection

亡梦爱人 提交于 2019-12-22 09:36:03

问题


I'm trying to load data from Office365 email without need for user interaction. I've created Azure App and I have Client ID and Client secret. I also have user information (email + password).

I need to call Office365 API to download emails from mailbox. But I need application to download them in background without user interaction (redirecting to MS/Office365 login page) to get authenticated/logged into mailbox.

Is there any way how to do this only through Office API, without need of redirection?

Thanks for any info.


回答1:


Yes, you are able to create a daemon service app using the Client Credential flow to authenticate the app.

Here is a code sample to retrieve the mails using Microsoft Graph SDK with this flow:

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);
}

And we need to register the app on the Azure AD portal and grant the app Mail.Read scope like figure below:

Refer to here for more detail about calling Microsoft Graph in a service or daemon app



来源:https://stackoverflow.com/questions/38371147/office365-authentication-without-login-redirection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!