来自WinForm的C#身份验证

时间:2018-04-12 15:06:19

标签: c# windows-authentication

我已准备好许多关于身份验证的SO文章,但无法使我的应用程序正常运行。我试图通过服务器REST api向服务器提供身份验证凭据以访问资源。当使用Sharepoint REST api(使用SharePointOnlineCredentials,最着名的是类的GetAuthenticationCookie方法)时,我能够做到这一点,但我相信我在此应用程序中的问题是缺少正确配置的身份验证cookie。我的代码供参考......

public static async Task<string> GetWebPageProjectData(string url)
    {
        string username = "SampleUser@Domain.com";
        string password = "SamplePassword#!";

        var credential = new System.Net.NetworkCredential(username, securePassword, "Domain");

        String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));

        HttpResponseMessage response = null;


        /* THE ISSUE IS THE LACK OF AN AUTHENTICATION COOKIE !?!?!    */
        try
        {
            using (var handler = new HttpClientHandler { Credentials = credential })
            {
                var uri = new Uri("http://webpage/location");


                // ***WORKS W/ SP credentials ***handler.CookieContainer.SetCookies(uri, credential.GetAuthenticationCookie(uri));
                //handler.CookieContainer.SetCookies()  What I think needs to be done in some way, shape, or form!?!?

                using (var client = new HttpClient(handler))
                {
                    client.DefaultRequestHeaders.Add("Authorization", "basic" + encoded);
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json;odata=nometadata"));

                    var query = url;
                    response = await client.GetAsync($"{query}").ConfigureAwait(false);

                    return await response.Content.ReadAsStringAsync();
                }
            }
        }//end try
        catch (HttpRequestException) 
        {
            return null;
        }
        catch (ArgumentNullException)
        {
            return null;
        }
        catch (CookieException)
        {
            return null;
        }

    }

我已尝试使用相同结果的此代码的众多变体(preAuthenticate,使用代理..)。最终我最终登录了我公司设置的登录页面,因为这是一个内部网Web应用程序......我在这里缺少什么?

0 个答案:

没有答案
相关问题