gpt4 book ai didi

c# - 在重定向时保持 HTTP 基本身份验证有效

转载 作者:太空狗 更新时间:2023-10-29 21:54:44 25 4
gpt4 key购买 nike

我们正在使用具有基本身份验证的网络服务。一切正常,直到 Web 服务的所有者实现平衡服务。这只是将请求重定向到不同的 Web 服务实例。

问题是在被重定向后基本认证失败。存在“请求身份验证凭据未通过”异常。

附加信息:

  1. 我们必须手动创建请求。

        var req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(Settings.Default.HpsmServiceAddress));

    req.Headers.Add("Authorization", "Basic aaaaaaaaaaa");
    req.PreAuthenticate = true;
    req.AuthenticationLevel = AuthenticationLevel.MutualAuthRequested;
    req.UserAgent = "Apache-HttpClient/4.1.1 (java 1.5)";
    req.KeepAlive = false;

    ServicePointManager.Expect100Continue = false;

    req.ContentType = "text/xml; charset=utf-8";
    req.Method = "POST";
    req.Accept = "gzip,deflate";
    req.Headers.Add("SOAPAction", actionName);
    byte[] buffer = Encoding.UTF8.GetBytes(envelop);
    Stream stm = req.GetRequestStream();
    stm.Write(buffer, 0, buffer.Length);
    stm.Close();

    WebResponse response = req.GetResponse();
    string strResponse = new StreamReader(response.GetResponseStream()).ReadToEnd();
    response.Dispose();
  2. 我们使用 HTTP 307 重定向进行重定向

最佳答案

按照 HttpWebRequest.AllowAutoRedirect 属性的 MSDN,我发现了这个:

The Authorization header is cleared on auto-redirects and HttpWebRequest automatically tries to re-authenticate to the redirected location. In practice, this means that an application can't put custom authentication information into the Authorization header if it is possible to encounter redirection. Instead, the application must implement and register a custom authentication module. The System.Net.AuthenticationManager and related class are used to implement a custom authentication module. The AuthenticationManager.Register method registers a custom authentication module.

解决方案是编写自定义身份验证模块。

这是我发现的:

http://msdn.microsoft.com/en-us/library/system.net.authenticationmanager.aspx

这里是 AllowAutoRedirect 属性页面:

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.allowautoredirect.aspx

更新

您可以尝试使用 CredentialCache 而不是向 webrequest 添加 header 吗?

CredentialCache myCache = new CredentialCache();

myCache.Add(
new Uri("http://www.contoso.com/"),"Basic",new NetworkCredential(UserName,SecurelyStoredPassword));
req.Credentials = myCache;

关于c# - 在重定向时保持 HTTP 基本身份验证有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14056766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com