根據MSDN,當HttpWebRequest.AllowAutoRedirect
屬性爲true時,重定向將清除驗證標頭。給出的解決方法是實施IAuthenticationModule辦理身份驗證:如何處理HttpWebRequest.AllowAutoRedirect的認證?
的授權頭在自動重定向清除,HttpWebRequest的自動嘗試重新進行身份驗證,以重定向的位置。實際上,這意味着如果應用程序可能遇到重定向,則無法將自定義身份驗證信息放入授權標頭。相反,應用程序必須實現並註冊一個自定義驗證模塊。 System.Net.AuthenticationManager和相關類用於實現自定義驗證模塊。 AuthenticationManager.Register方法註冊一個自定義認證模塊。
我創造了這個接口的基本實現:
public class CustomBasic : IAuthenticationModule
{
public CustomBasic() { }
public string AuthenticationType { get { return "Basic"; } }
public bool CanPreAuthenticate { get { return true; } }
private bool checkChallenge(string challenge, string domain)
{
if (challenge.IndexOf("Basic", StringComparison.InvariantCultureIgnoreCase) == -1) { return false; }
if (!string.IsNullOrEmpty(domain) && challenge.IndexOf(domain, StringComparison.InvariantCultureIgnoreCase) == -1) { return false; }
return true;
}
public Authorization PreAuthenticate(WebRequest request, ICredentials credentials)
{
return authenticate(request, credentials);
}
public Authorization Authenticate(String challenge, WebRequest request, ICredentials credentials)
{
if (!checkChallenge(challenge, string.Empty)) { return null; }
return this.authenticate(request, credentials);
}
private Authorization authenticate(WebRequest webRequest, ICredentials credentials)
{
NetworkCredential requestCredentials = credentials.GetCredential(webRequest.RequestUri, this.AuthenticationType);
return (new Authorization(string.Format("{0} {1}", this.AuthenticationType, Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", requestCredentials.UserName, requestCredentials.Password))))));
}
}
和一個簡單的驅動程序行使功能:
public class Program
{
static void Main(string[] args)
{
// replaces the existing handler for Basic authentication
AuthenticationManager.Register(new CustomBasic());
// make a request that requires authentication
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://www.SomeUrlThatRequiresAuthentication.com");
request.Method = "GET";
request.KeepAlive = false;
request.ContentType = "text/plain";
request.AllowAutoRedirect = true;
request.Credentials = new NetworkCredential("userName", "password");
HttpWebResponse result = (HttpWebResponse)request.GetResponse();
}
}
當我做不重定向的請求我的班級上的Authenticate
方法被調用,並且驗證成功。當我發出請求重新生成307(臨時重定向)響應時,我的類的任何方法都不會被調用,並且認證失敗。這裏發生了什麼?
我寧願不禁用自動重定向並編寫自定義邏輯來自己處理3xx響應。我怎樣才能讓我的身份驗證邏輯與自動重定向一起工作?
你可以試試這個?或者將重定向網址放在請求行中?對此不太瞭解,但也許有幫助 –
FWIW,我有完全相同的問題並尋找解決方案。 – tomo