Вход на сайт https с помощью C # - PullRequest
5 голосов
/ 30 января 2011

Я пытаюсь написать небольшую программу, которая регистрируется на веб-сайте Verizon, а затем проверяет, сколько минут осталось на месяц.Мне нужна помощь, чтобы выяснить, как войти на сайт с помощью C #.Я знаю, что мне нужно использовать веб-запрос для публикации информации для входа в систему, но я не знаю, как это сделать.Сайт с формой входа - https://login.verizonwireless.com/amserver/UI/Login,, но я не уверен, какую информацию я должен опубликовать на сайте для входа и как это сделать.Ниже то, что я нашел для источника на сайте.Если кто-то может помочь мне понять, как войти в систему с C #, я был бы очень признателен.Спасибо за любую помощь.

form method = "post" autocomplete = "off" action = "https://login.verizonwireless.com:443/amserver/UI/Login" name =" loginForm "id =" loginForm "onsubmit =" return disableBut ();">
input type =" hidden "name =" realm "value =" vzw "/>
input type =" hidden "name =" goto "value =" "/>
input type ="hidden "name =" gotoOnFail "value =" "/>
тип ввода =" hidden "name =" gx_charset "value =" UTF-8 "/>
тип ввода =" hidden "name =" запомнитьUserNameCheckBoxExists "value = "Y" />
h2 style = "padding-left: 0px;"> Войдите в My Verizon
div class = "clear10"> / div>

Ответы [ 2 ]

2 голосов
/ 30 января 2011

Прежде всего, вам не хватает двух важных полей :) Если вы посмотрите на HTML, в форме есть два дополнительных поля - IDToken1 (это имя пользователя) и IDToken2 (это пароль).).

Если вы предоставите их для запроса POST, вы должны вернуть некоторые файлы cookie, которые затем можно будет использовать при последующих запросах.Они идентифицируют вас как вошедшего в систему пользователя.

Конечно, я не могу полностью протестировать это, так как у меня нет действительного логина, но вот начало:

class VerizonLogin
{
    CookieContainer Cookies = new CookieContainer();

    void Main()
    {
        Login("test","testpass");

        // Now the cookies in "Cookies" are all set.
        // Ensure you set CookieContainer on all subsequent requests
    }

    void Login(string username, string password)
    {
        var wr = (HttpWebRequest)WebRequest.Create("https://login.verizonwireless.com:443/amserver/UI/Login");
        wr.Method = "POST";
        wr.ContentType = "application/x-www-form-urlencoded";
        wr.Referer = "https://login.verizonwireless.com/amserver/UI/Login"; // my tests show this is needed
        wr.CookieContainer = Cookies;

        var parameters = new Dictionary<string,string>{
            {"realm", "vzw"},
            {"goto",""},
            {"gotoOnFail",""},
            {"gx_charset", "UTF-8"},
            {"rememberUserNameCheckBoxExists","Y"},
            {"IDToken1", username},
            {"IDToken2", password}
        };

        using (var requestStream = wr.GetRequestStream())
        using (var writer = new StreamWriter(requestStream,Encoding.UTF8))
            writer.Write(ParamsToFormEncoded(parameters));

        using (var response = (HttpWebResponse)wr.GetResponse())
        {
            // here you need to detect a correct login... this might be one of the cookies.
            // if incorrect throw an exception or something.
        }
    }

    string ParamsToFormEncoded(Dictionary<string,string> parameters)
    {
        return string.Join("&", parameters.Select(kvp => 
            Uri.EscapeDataString(kvp.Key).Replace("%20","+") + "=" + Uri.EscapeDataString(kvp.Value).Replace("%20","+")
        ).ToArray());
    }
}
1 голос
/ 30 января 2011

Вот 2 функции, которые вам нужны для этого. Да, вы правы, вы должны использовать веб-запрос, но существует обратный вызов, который вам необходимо создать для проверки сертификата из https. Вы должны быть в состоянии использовать их прямо из коробки.

C #

private bool ValidateCert(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    return true;
}

private string PostToSite(string url)
{
    string result = string.empty;

    byte[] postBuffer = System.Text.Encoding.GetEncoding(1252).GetBytes("realm=vzw&goto=&gotoOnFail=&gx_charset=UTF-8&rememberUserNameCheckBoxExists=Y");

    HttpWebRequest webRequest = (HttpWebRequest)Net.WebRequest.Create(_endpoint);
    webRequest.KeepAlive = false;
    webRequest.AllowAutoRedirect = false;

    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(ValidateCert);

    webRequest.ContentLength = postBuffer.Length;
    webRequest.Method = "POST";
    webRequest.ContentType = "application/x-www-form-urlencoded";

    using (Stream str = webRequest.GetRequestStream()) {
        str.Write(postBuffer, 0, postBuffer.Length);
    }

    using (System.Net.HttpWebResponse res = (HttpWebResponse)webRequest.GetResponse()) {
        using (StreamReader sr = new StreamReader(res.GetResponseStream())) {
            result = sr.ReadToEnd();
        }
    }

    return result;
}

VB.NET

Private Function ValidateCert(ByVal sender As Object, ByVal certificate As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As System.Net.Security.SslPolicyErrors) As Boolean
 Return True
End Function

Private Function PostToSite(url as string) as string
    Dim result as string = string.empty

    Dim postBuffer As Byte() = System.Text.Encoding.GetEncoding(1252).GetBytes("realm=vzw&goto=&gotoOnFail=&gx_charset=UTF-8&rememberUserNameCheckBoxExists=Y")

    Dim webRequest As HttpWebRequest = CType(Net.WebRequest.Create(_endpoint), HttpWebRequest)
    webRequest.KeepAlive = False
    webRequest.AllowAutoRedirect = False

    ServicePointManager.ServerCertificateValidationCallback = New System.Net.Security.RemoteCertificateValidationCallback(AddressOf ValidateCert)

    webRequest.ContentLength = postBuffer.Length
    webRequest.Method = "POST"
    webRequest.ContentType = "application/x-www-form-urlencoded"

    Using str As Stream = webRequest.GetRequestStream()
        str.Write(postBuffer, 0, postBuffer.Length)
    End Using

    Using res As System.Net.HttpWebResponse = CType(webRequest.GetResponse(), HttpWebResponse)
        Using sr As New StreamReader(res.GetResponseStream())
            result = sr.ReadToEnd()
        End Using
    End Using

    return result
End Function
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...