POST запрос по HTTPS не отправляется - C#
Формулировка задачи:
Всем привет. На данном форуме очень много похожих тем, но они так и не раскрыли данного вопроса.
Пытаюсь авторизоваться в личном кабинете сервиса МегаФон:
https
://lk.megafon.ru Я перепробовал очень много вариантов, прикручивал разные сертификаты и все тщетно.- Если обращаться
GET
запросом, прикидываясь браузером, в ответ я получаю - ничего. А нужно получить значение параметраCSRF_PARAM
, чтобы передать его совместно с логином/паролем при авторизации. - Когда я впервые обращаюсь к сервису без настроек
HttpWebRequest
. Мне приходит ~7000 символов, среди которых естьCSRF_PARAM
. - Далее я формирую
POST
запрос и передаю три параметра на форму входа по адресу:https
://lk.megafon.ru/doLogin. - Если включить автоматическую переадресацию, В ответ от сервера я получаю страницу авторизации. (т.е. снова здорова)
- Если не включать переадресацию. В ответ ошибка. StatusCode = "Found"
POST
запрос вообще не отправлял и никаких данных нет. (Fiddler4 ловит HTTPS после установки в него сертификата. В браузере ловит все отлично) private static HttpWebRequest webRequest;
static void Main(string[] args)
{
CookieContainer cc = new CookieContainer();
HttpWebResponse resp;
try
{
webRequest = (HttpWebRequest)WebRequest.Create("https://lk.megafon.ru/dologin");
//webRequest.Headers = new WebHeaderCollection();
//webRequest.Headers.Add("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3");
//webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
//webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
//webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
webRequest.Method = "GET";
webRequest.AllowAutoRedirect = true;
webRequest.CookieContainer = new CookieContainer();
resp = (HttpWebResponse)webRequest.GetResponse();
var stream_ = new System.IO.StreamReader(resp.GetResponseStream());
var html = new System.Text.StringBuilder(stream_.ReadToEnd());
string CSRF = string.Empty;
Regex regex = new Regex(@"<input\s*name=CSRF.*?\s*value=""(?<text>[^""]+)"".*?", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
Match match = regex.Match(html.ToString());
if (match.Success)
CSRF = match.Groups["text"].Value;
else
return;
foreach (Cookie cookie in resp.Cookies)
{
cc.Add(cookie);
};
if (resp.ResponseUri.AbsolutePath == "/login/")
{
string webview = String.Format("CSRF={0}&j_username= номертелефона &j_password= пароль ", CSRF);
byte[] postBytes = Encoding.ASCII.GetBytes(webview);
// Получаем хранилеще сертификатов
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, false);
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptCertificate);
webRequest = (HttpWebRequest)WebRequest.Create("https://lk.megafon.ru/dologin");
//webRequest.Headers = new WebHeaderCollection();
//webRequest.Headers.Add("Accept-Language", "ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3");
//webRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
//webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0";
//webRequest.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
// Присваиваем сертификат для lk.megafon.ru по серийному номеру
for (int i = 0; i < certs.Count; i++)
{
X509Certificate2 a = certs[i];
if (certs[i].SerialNumber == "A10BCE32ECEF338D45639FFC594FC9CE")
webRequest.ClientCertificates.Add(certs[i]);
}
webRequest.Credentials = CredentialCache.DefaultCredentials;
webRequest.CookieContainer = cc;
webRequest.KeepAlive = true;
webRequest.ProtocolVersion = HttpVersion.Version10;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postBytes.Length;
webRequest.Proxy = null;
webRequest.AllowAutoRedirect = false;
Stream requestStream = webRequest.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
var resp2 = (HttpWebResponse)webRequest.GetResponse();
}
}
catch (WebException e)
{
if (e.Status != WebExceptionStatus.RequestCanceled)
{
}
return;
}
}
private static bool AcceptCertificate(object sender, System.Security.Cryptography.X509Certificates.X509Certificate xl, System.Security.Cryptography.X509Certificates.X509Chain xc, System.Net.Security.SslPolicyErrors spe)
{
if ((spe & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) == System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors)
{
return false;
}
else if ((spe & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) == System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch)
{
Zone z = Zone.CreateFromUrl(((HttpWebRequest)sender).RequestUri.ToString());
if (z.SecurityZone == System.Security.SecurityZone.Intranet
|| z.SecurityZone == System.Security.SecurityZone.MyComputer)
{
return true;
}
return false;
}
else if ((spe & System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable) == System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable)
{
return false;
}
return true;
}Решение задачи: «POST запрос по HTTPS не отправляется»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MegaFon
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
string host = "https://lk.megafon.ru";
Https https = new Https();
HttpResponse response = https.GET(host, new CookieContainer());
if (response.StatusCode == HttpStatusCode.OK)
{
string CSRF = GetParam("CSRF", response.Content);
if (CSRF == null)
throw new ArgumentNullException();
NameValueCollection parameters = new NameValueCollection();
parameters.Add("CSRF", System.Uri.EscapeDataString(CSRF));
parameters.Add("j_username", "");
parameters.Add("j_password", "");
response = https.POST(host + "/dologin/", GetCookie(response.Cookies), parameters);
var body = response.Content;
}
}
catch (Exception)
{
throw;
}
}
private CookieContainer GetCookie(CookieCollection cookies)
{
CookieContainer cc = new CookieContainer();
cc.Add(cookies);
return cc;
}
private string GetParam(string param, string content)
{
Regex regex = new Regex(String.Format(@"<input\s*name={0}.*?\s*value=""(?<text>[^""]+)"".*?", param), RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Singleline);
Match match = regex.Match(content);
if (match.Success)
return match.Groups["text"].Value;
else
return null;
}
}
}