使用microsoft graph对web api进行无需登录的用户身份验证

时间:2018-01-09 15:46:09

标签: c# microsoft-graph asp.net-core-webapi

我想在使用.net core 2.0的web api中使用microsoft graph,我想在没有登录提示的情况下对用户进行身份验证。

以下是我使用的代码,如果我的方法错误,请纠正我。

    string clientId = "";
    string clientsecret = "";
    string tenant = "";
    string resourceURL = "https://graph.microsoft.com";

    string userMail = "testuser3@company.com";
    public async Task<string> GetMyEmailUser()
    {
        try
        {
            var result = "";


            string AzureADAuthority = "https://login.microsoftonline.com/companyname.com";

            AuthenticationContext authenticationContext = new AuthenticationContext(AzureADAuthority, false);


            var credential = new ClientCredential(clientId, clientsecret);


            var authenticationResult =  authenticationContext.AcquireTokenAsync(resourceURL, credential).Result;
           var token = authenticationResult.AccessToken;


            using (var confClient = new HttpClient())
            {
                var url = "https://graph.microsoft.com/v1.0";
                confClient.BaseAddress = new Uri(url);
            confClient.DefaultRequestHeaders.Accept.Clear();
            confClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            confClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

               var response = confClient.GetAsync(url + "/me/mailFolders/inbox/messages?$filter=isRead eq false&$top=100").Result;

                var jsonString = JObject.Parse(await response.Content.ReadAsStringAsync());

                 IUserMessagesCollectionPage myDetails = JsonConvert.DeserializeObject<IUserMessagesCollectionPage>(jsonString["value"].ToString());
            }

我是微软图表的新手,非常感谢您的帮助。感谢。

0 个答案:

没有答案