HttpWebRequest使用基本身份验证

时间:2010-12-02 11:36:27

标签: c# authentication credentials webrequest

我正在尝试通过一个身份验证请求来模仿我们在为此行为设置IIS时常常看到的“基本身份验证请求”。

网址为: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();

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

  

基础连接已关闭:发生意外错误   发送。

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

10 个答案:

答案 0 :(得分:226)

您也可以自己添加授权标题。

只需将名称“授权”和值“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);

修改

根据What encoding should I use for HTTP Basic Authentication?和Jeroen的评论,将编码从UTF-8切换到ISO 8859-1。

答案 1 :(得分:49)

我终于明白了!

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;

这是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;
}

YAY!

答案 2 :(得分:27)

如果您可以使用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");

答案 3 :(得分: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; 

答案 4 :(得分:2)

对于使用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;

答案 5 :(得分:1)

规范可以读作" ISO-8859-1"或"未定义"。你的选择。众所周知,许多服务器使用ISO-8859-1(喜欢或不喜欢),并且在发送其他内容时会失败。

有关更多信息和解决问题的建议,请参阅http://greenbytes.de/tech/webdav/draft-reschke-basicauth-enc-latest.html

答案 6 :(得分:1)

如果实现了基本身份验证和代理,以下代码将解决json响应。此外,IIS 7.5 Hosting Problm将解析。

public string HttpGetByWebRequ(string uri, string username, string password)
{
//For Basic Authentication
    string authInfo = username + ":" + password;
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));

//For Proxy
    WebProxy proxy = new WebProxy("http://10.127.0.1:8080", true);

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "GET";
    request.Accept = "application/json; charset=utf-8";
    request.Proxy = proxy;

    request.Headers["Authorization"] = "Basic " + authInfo;

    var response = (HttpWebResponse)request.GetResponse();

    string strResponse = "";
    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        strResponse= sr.ReadToEnd();

    }

    return strResponse;
}

答案 7 :(得分:0)

以下构造对我而言无法正常工作:

request.Credentials = new NetworkCredential("user", "pass");

我改用CredentialCache

CredentialCache credentialCache = new CredentialCache
{
    {
        new Uri($"http://{request.Host}/"), "Basic",
        new NetworkCredential("user", "pass")
    }
};
request.Credentials = 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);
    }
}

我希望它将对将来的人有所帮助。

答案 8 :(得分:0)

对我来说,第一件事是ServicePointManager.SecurityProtocol = SecurityProtocolType。 Tls12 代替了Ssl3。

其次,我必须发送Basic Auth请求以及一些数据(采用表单编码)。在尝试了许多解决方案之后,这是对我非常有用的完整示例。

免责声明:以下代码是在此链接和一些其他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();

答案 9 :(得分:0)

最重要的答案和其他答案无法为您效劳的一个原因是,因为它缺少关键线。 (请注意,许多API手册都没有此必要)

request.PreAuthenticate = true;