C# 重定向时保持HTTP基本身份验证处于活动状态

C# 重定向时保持HTTP基本身份验证处于活动状态,c#,web-services,http,http-headers,basic-authentication,C#,Web Services,Http,Http Headers,Basic Authentication,我们正在使用具有基本身份验证的web服务。 在web服务的所有者实现平衡服务之前,一切都很顺利。 它只是将请求重定向到web服务的不同实例 问题是在被重定向后,基本身份验证失败。 存在“请求身份验证凭据未通过”异常 其他信息: 我们必须手动创建请求 var req = (HttpWebRequest)WebRequest.CreateDefault(new Uri(Settings.Default.HpsmServiceAddress)); req.Headers.Add("A

我们正在使用具有基本身份验证的web服务。 在web服务的所有者实现平衡服务之前,一切都很顺利。 它只是将请求重定向到web服务的不同实例

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

其他信息:

  • 我们必须手动创建请求

        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();
    
  • 我们使用HTTP 307重定向进行重定向


  • 按照我找到的HttpWebRequest.AllowAutoRedirect属性的MSDN进行操作:

    自动重定向时,授权标头被清除并且 HttpWebRequest自动尝试重新验证到 重定向位置。实际上,这意味着应用程序不能 如果需要,请将自定义身份验证信息放入授权标头 可能会遇到重定向。相反,应用程序必须 实现并注册自定义身份验证模块。这个 System.Net.AuthenticationManager和相关类用于 实现自定义身份验证模块。这个 AuthenticationManager.Register方法注册自定义 身份验证模块

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

    以下是我对它的发现:

    这里是AllowAutoRedirect属性页:

    更新 您是否可以尝试使用CredentialCache而不是向webrequest添加标题

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

    事实上,
    CredentialCache
    工作正常。但是,如果您想添加多个基本身份验证凭据(例如,如果您知道存在重定向),则可以使用我创建的以下函数:

    private void SetNetworkCredential(Uri uriPrefix, string authType, NetworkCredential credential)
    {
        if (request.Credentials == null)
        {
            request.Credentials = new CredentialCache();
        }
    
        if (request.Credentials.GetCredential(uriPrefix, authType) == null)
        {
            (request.Credentials as CredentialCache).Add(uriPrefix, authType, credential);
        }
    }
    

    我希望它将来能帮助别人。

    Tnx。这看起来像是解决方案,但仍然不起作用=(我添加了以下几行:req.AllowAutoRedirect=true;AuthenticationManager.Unregister(“基本”);AuthenticationManager.Register(new CustomBasic());req.Credentials=new NetworkCredential(“用户”、“密码”);其中CustomBasic()这只是你链接示例中的代码。它在服务实例中运行良好,但重定向后失败。你知道我做错了什么吗?Tnx。它可以运行!!!!你能评论一下有什么不同,以及为什么通常的凭据不起作用吗?