HttpWebRequest使用基本身份验证

Ken*_*llo 130 c# authentication credentials webrequest

我正在尝试通过一个身份验证请求来模仿我们习惯在为此行为设置IIS时看到的"基本身份验证请求".

URL为:https
://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC =22&SC=1&ST=2(警告:https!)

此服务器在UNIX和Java下作为应用程序服务器运行.

这是我用来连接到此服务器的代码:

CookieContainer myContainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2");
request.Credentials = new NetworkCredential(xxx,xxx);
request.CookieContainer = myContainer;
request.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Run Code Online (Sandbox Code Playgroud)

(我从本网站上的另一篇文章中复制了此内容).但我从服务器收到这个答案:

底层连接已关闭:发送时发生意外错误.

我想我尝试了所有可能的任务,我对C#的知识必须提供给我,但没有...

Zam*_*lli 249

您也可以自己添加授权标头.

只需将名称命名为"Authorization",并将值设置为"Basic BASE64({USERNAME:PASSWORD})"

String username = "abc";
String password = "123";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
Run Code Online (Sandbox Code Playgroud)

编辑

将编码从UTF-8切换到ISO 8859-1每个编码应该用于HTTP基本身份验证吗?和Jeroen的评论.

  • 因此,您如何确定UTF8是正确使用的编码? (2认同)
  • 不错的收获。看起来请求Authentication标头应以ISO-8859-1编码。根据http://stackoverflow.com/questions/7242316/what-encoding-should-i-use-for-http-basic-authentication (2认同)

Ken*_*llo 53

我终于明白了!

string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
WebRequest request = WebRequest.Create(url);
request.Credentials = GetCredential();
request.PreAuthenticate = true;
Run Code Online (Sandbox Code Playgroud)

这是 GetCredential()

private CredentialCache GetCredential()
{
    string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
    CredentialCache credentialCache = new CredentialCache();
    credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(ConfigurationManager.AppSettings["ead_username"], ConfigurationManager.AppSettings["ead_password"]));
    return credentialCache;
}
Run Code Online (Sandbox Code Playgroud)

好极了!


Tam*_*mir 28

如果您可以使用WebClient该类,则使用基本身份验证变得简单:

var client = new WebClient {Credentials = new NetworkCredential("user_name", "password")};
var response = client.DownloadString("https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2");
Run Code Online (Sandbox Code Playgroud)


MrE*_*yes 8

试试这个:

System.Net.CredentialCache credentialCache = new System.Net.CredentialCache(); 
credentialCache.Add(
    new System.Uri("http://www.yoururl.com/"),
    "Basic", 
    new System.Net.NetworkCredential("username", "password")
);

...
...

httpWebRequest.Credentials = credentialCache; 
Run Code Online (Sandbox Code Playgroud)


小智 6

首先,对我来说 ServicePointManager.SecurityProtocol = SecurityProtocolType。Tls12代替 Ssl3 工作。

其次,我必须发送基本身份验证请求以及一些数据(表单 urlencoded)。在尝试了许多解决方案之后,这是对我来说非常有效的完整示例。

免责声明:下面的代码是在此链接和其他一些 stackoverflow 链接上找到的解决方案的混合体,感谢您提供有用的信息。

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        String username = "user_name";
        String password = "password";
        String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));

        //Form Data
        var formData = "var1=val1&var2=val2";
        var encodedFormData = Encoding.ASCII.GetBytes(formData);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("THE_URL");
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = "POST";
        request.ContentLength = encodedFormData.Length;
        request.Headers.Add("Authorization", "Basic " + encoded);
        request.PreAuthenticate = true;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(encodedFormData, 0, encodedFormData.Length);
        }

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Run Code Online (Sandbox Code Playgroud)


Ale*_*xei 5

对于使用这些RestSharp,它可能使用时失败SimpleAuthenticator(不使用ISO-8859-1幕后可能是由于)。我设法通过显式发送基本身份验证标头来完成此操作:

string username = "...";
string password = "...";

public IRestResponse GetResponse(string url, Method method = Method.GET)
{
    string encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{username}:{password}"));
    var client = new RestClient(url);
    var request = new RestRequest(method );
    request.AddHeader("Authorization", $"Basic {encoded}");
    IRestResponse response = client.Execute(request);
    return response;
}

var response = GetResponse(url);
txtResult.Text = response.Content;
Run Code Online (Sandbox Code Playgroud)