Authenticate user without login for web api using microsoft graph

三世轮回 提交于 2019-12-11 14:23:10

问题


I want to use microsoft graph in web api which is using .net core 2.0, I want to authenticate user without login prompt.

Following is the code I have used, Please correct me if my method is wrong.

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

I am new to microsoft graph and would really appreciate your help. Thanks.

来源:https://stackoverflow.com/questions/48171865/authenticate-user-without-login-for-web-api-using-microsoft-graph

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