【发布时间】:2019-10-11 15:28:54
【问题描述】:
我需要将 Web 应用程序之外的用户重定向到使用基本身份验证的页面。
这是我一直在尝试的:
HttpWebRequest req = WebRequest.Create(url) as HttpWebRequest;
String username = "username";
String password = "password";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
req.Headers.Add("Authorization", "Basic " + encoded);
HttpWebResponse response = req.GetResponse() as HttpWebResponse;
return this.Redirect(response.ResponseUri.ToString());
我也尝试过缓存方案,但没有成功:
CredentialCache myCache = new CredentialCache();
myCache.Add(new Uri(url), "Basic", new NetworkCredential(username, password));
req.Credentials = myCache;
我能得到一些帮助吗?
【问题讨论】:
-
标准基本身份验证只需要
req.Credentials = new NetworkCredential(username, password);。但这取决于您要连接的服务。您也可以添加req.PreAuthenticate = true;,它在某些情况下效果更好。如果您必须使用标头,请将其添加到HttpRequestHeader.Authorization并使用UTF8或ASCII对凭证进行编码。ISO-8859-1可能不正确,这取决于实际使用的字符集。
标签: c# asp.net authentication asp.net-core httpwebrequest