2016-08-08 44 views
2

我正在嘗試登錄到使用HTTP基本身份驗證的服務器(REST API)。請求看起來是這樣的:C#HTTP基本身份驗證憑據發送得太早

public JObject PerformLogin(string username, string password) 
{ 
    string html = string.Empty; 

    this.username = username; 
    this.password = password; 

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(auth_url_internal); 
    request.AllowAutoRedirect = true; 
    request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; 
    request.Method = "GET"; 
    request.CookieContainer = cookies; 
    request.KeepAlive = true; 
    //request.ServicePoint.Expect100Continue = false; 
    request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; 
    request.Headers.Add("Accept-Language", "de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4"); 
    request.PreAuthenticate = true; 
    request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested; 

    string authInfo = username + ":" + password; 
    authInfo = Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(authInfo)); 
    request.Headers.Add("Authorization", "Basic " + authInfo); 

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
    using (Stream stream = response.GetResponseStream()) 
    using (StreamReader reader = new StreamReader(stream)) 
    { 
     html = reader.ReadToEnd(); 
    } 

    JObject jresponse = JObject.Parse(html); 

    sess_url_internal = jresponse["internalUrl"].ToString(); 
    sess_url_public = jresponse["publicUrl"].ToString(); 

    return jresponse; 
} 

它基本上工作,但是憑據發送得太早。

首先,我使用curl詳細查看流量的詳細信息,並找到了「Location:」 - Header,這意味着發生了重定向。詳細地說,服務器將我從/api/rest/authenticate?version=1.0(它是認證URL(可稱爲URL1))重定向到/authenticationbasic/login?AlcApplicationUrl=/api/rest/authenticate%3fversion=1.0(URL2)。

但是,Chrome會將憑據發送到URL2,在那裏我的程序將它們發送到URL1,因爲服務器期望它們位於URL2,我的應用程序不會發送任何信息,因此會得到錯誤返回。

我該如何改變這種行爲?

+0

設爲false'request.AllowAutoRedirect = FALSE;',做你自己重定向。 –

+0

我該如何「做我自己的重定向」?所以基本上等待respose,尋找一個'Location'標題,如果存在,對該位置做另一個響應? –

+1

是......你知道了...... = =) –

回答

1

因此與x...的熱心幫助我想出如何做到這一點:

HttpWebResponse response = (HttpWebResponse)request.GetResponse();後只需添加

if ((int)response.StatusCode == 302) // redirect 
{ 
    /* 
     Call the function recursively with the new URL, found in 
     response.Headers["Location"], in my case this would be: 
    */ 

    auth_url_internal = response.Headers["Location"]; 
    return PerformLogin(username, password); 
}