Мне всегда было интересно, как заставить HttpClient
работать с куками подобно браузеру, затем сохранять их при выходе из приложения, и продолжить использовать после повторного запуска. И вот, наконец, приспичило, и я сделал.
Реализовал работу HttpClient
следующим образом:
Код для инспекции
public static class HttpManager
{
private static readonly HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.All
};
private static readonly HttpClient client = new HttpClient(handler)
{
DefaultRequestVersion = HttpVersion.Version20
};
static HttpManager()
{
client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0");
}
// GET
public static async Task<string> GetPageAsync(string url)
{
using HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
return await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
}
// POST
public static async Task<string> PostFormAsync(string url, Dictionary<string, string> data)
{
using HttpContent content = new FormUrlEncodedContent(data);
using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url) { Content = content };
using HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
return await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
}
// Загрузить и расшифровать Cookie из файла
public static async Task LoadCookiesAsync(string filename)
{
if (File.Exists(filename))
{
using FileStream fs = File.OpenRead(filename);
byte[] IV = new byte[16];
fs.Read(IV);
byte[] protectedKey = new byte[178];
fs.Read(protectedKey);
using AesManaged aes = new AesManaged
{
Key = ProtectedData.Unprotect(protectedKey, IV, DataProtectionScope.CurrentUser),
IV = IV
};
using CryptoStream cs = new CryptoStream(fs, aes.CreateDecryptor(), CryptoStreamMode.Read, true);
CookieCollection cookies = await JsonSerializer.DeserializeAsync<CookieCollection>(cs);
foreach (Cookie cookie in cookies)
{
// не загружать, если кука заэкспайрилась
if (!cookie.Expired && (cookie.Expires == DateTime.MinValue || cookie.Expires > DateTime.Now))
handler.CookieContainer.Add(cookie);
}
}
}
// Зашифровать и сохранить Cookie в файл
public static async Task SaveCookiesAsync(string filename)
{
using AesManaged aes = new AesManaged();
using FileStream fs = File.Create(filename);
fs.Write(aes.IV);
fs.Write(ProtectedData.Protect(aes.Key, aes.IV, DataProtectionScope.CurrentUser));
using CryptoStream cs = new CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Write, true);
await JsonSerializer.SerializeAsync(cs, handler.CookieContainer.GetAllCookies());
}
}
public static class CookieContainerExtensions
{
// Забирает все куки из контейнера
public static CookieCollection GetAllCookies(this CookieContainer container)
{
CookieCollection allCookies = new CookieCollection();
IDictionary domains = (IDictionary)container.GetType()
.GetRuntimeFields()
.FirstOrDefault(x => x.Name == "m_domainTable")
.GetValue(container);
foreach (object field in domains.Values)
{
IDictionary values = (IDictionary)field.GetType()
.GetRuntimeFields()
.FirstOrDefault(x => x.Name == "m_list")
.GetValue(field);
foreach (CookieCollection cookies in values.Values)
{
allCookies.Add(cookies);
}
}
return allCookies;
}
}
Куки сериализуются в Json, шифруются с защитой ключа через DPAPI и сохраняются на диск.
Воспроизводимый пример, работающий с инспектируемым кодом
Авторизация на StackOverflow с логином и паролем
using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;
private const string filename = "cookies.bin";
static async Task Main(string[] args)
{
await HttpManager.LoadCookiesAsync(filename);
string html = await HttpManager.GetPageAsync("https://ru.stackoverflow.com/");
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(html);
if (doc.DocumentNode.QuerySelector(".top-bar ol").HasClass("user-logged-out"))
{
html = await HttpManager.GetPageAsync("https://ru.stackoverflow.com/users/login?ssrc=head&returnurl=https%3a%2f%2fru.stackoverflow.com%2f");
doc = new HtmlDocument();
doc.LoadHtml(html);
string fkey = doc.DocumentNode.QuerySelector("form#login-form input[name=fkey]").Attributes["value"].Value;
string ssrc = doc.DocumentNode.QuerySelector("form#login-form input[name=ssrc]").Attributes["value"].Value;
Console.Write("Login: ");
string login = Console.ReadLine();
Console.Write("Password: ");
string password = ReadPassword();
Dictionary<string, string> formData = new Dictionary<string, string>
{
{ "fkey", fkey },
{ "ssrc", ssrc },
{ "email", login },
{ "password", password },
{ "oauth_version", "" },
{ "oauth_server", "" }
};
html = await HttpManager.PostFormAsync("https://ru.stackoverflow.com/users/login?ssrc=head&returnurl=https%3a%2f%2fru.stackoverflow.com%2f", formData);
doc = new HtmlDocument();
doc.LoadHtml(html);
}
string user = doc.DocumentNode.QuerySelector(".top-bar ol .my-profile span.v-visible-sr").InnerText;
Console.WriteLine(user);
string rep = HtmlEntity.DeEntitize(doc.DocumentNode.QuerySelector(".top-bar ol .my-profile div.-rep").Attributes["title"].Value);
Console.WriteLine(rep);
string badges = string.Join(Environment.NewLine, doc.DocumentNode.QuerySelectorAll(".top-bar ol .my-profile div.-badges span.v-visible-sr").Select(x => x.InnerText));
Console.WriteLine(badges);
await HttpManager.SaveCookiesAsync(filename);
Console.ReadKey();
}
private static string ReadPassword()
{
string password = string.Empty;
ConsoleKey key;
do
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
key = keyInfo.Key;
if (key == ConsoleKey.Backspace && password.Length > 0)
{
Console.Write("\b \b");
password = password[0..^1];
}
else if (!char.IsControl(keyInfo.KeyChar))
{
Console.Write("*");
password += keyInfo.KeyChar;
}
} while (key != ConsoleKey.Enter);
Console.WriteLine();
return password;
}
Вывод в консоль при первом запуске с запросом учетных данных
Login: <my_email>@<censored>.ru
Password: ********************
aepot
ваша репутация: 4,904
2 золотых знака
5 серебряных знаков
25 бронзовых знаков
Вывод в консоль при повторном запуске приложения, автоматически используются куки для авторизации
aepot
ваша репутация: 4,904
2 золотых знака
5 серебряных знаков
25 бронзовых знаков
Воспроизводимый пример не нужно инспектировать, я знаю, что в нем не учтены сценарии ошибок при вводе пароля или если вход по паролю не поддерживается учетной записью.
Кстати! Чтобы работало, нужно, чтобы в параметрах безопасности учетной записи StackExchange был активен способ входа по логину и паролю.
Посмотрите пожалуйста код класса HttpManager
, есть ли что улучшить или сделать по-другому? Я раньше не работал с Cookie.
Обновление - с использованием BinaryFormatter
По совету от @ヒミコ попробовал реализацию с использованием BinaryFormatter
. Тоже работает. Из плюсов - теперь не нужен дополнительный метод для извлечения кук, а CookieContainer
сохраняется "как есть". Пока не понял, что лучше, но Microsoft ругает BinaryFormatter
как небезопасный.
BinaryFormatter
is insecure and can't be made secure. For more information, see the BinaryFormatter security guide.
public static class HttpManager
{
private static readonly HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.All
};
private static readonly HttpClient client = new HttpClient(handler)
{
DefaultRequestVersion = HttpVersion.Version20
};
static HttpManager()
{
client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0");
}
public static async Task<string> GetPageAsync(string url)
{
using HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead);
return await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
}
public static async Task<string> PostFormAsync(string url, Dictionary<string, string> data)
{
using HttpContent content = new FormUrlEncodedContent(data);
using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url) { Content = content };
using HttpResponseMessage response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
return await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
}
public static async Task LoadCookiesAsync(string filename)
{
if (File.Exists(filename))
{
using FileStream fs = File.OpenRead(filename);
byte[] IV = new byte[16];
await fs.ReadAsync(IV);
byte[] protectedKey = new byte[178];
await fs.ReadAsync(protectedKey);
using AesManaged aes = new AesManaged
{
Key = ProtectedData.Unprotect(protectedKey, IV, DataProtectionScope.CurrentUser),
IV = IV
};
using CryptoStream cs = new CryptoStream(fs, aes.CreateDecryptor(), CryptoStreamMode.Read, true);
handler.CookieContainer = new BinaryFormatter().Deserialize(cs) as CookieContainer ?? new CookieContainer();
}
}
public static async Task SaveCookiesAsync(string filename)
{
using AesManaged aes = new AesManaged();
using FileStream fs = File.Create(filename);
await fs.WriteAsync(aes.IV);
await fs.WriteAsync(ProtectedData.Protect(aes.Key, aes.IV, DataProtectionScope.CurrentUser));
using CryptoStream cs = new CryptoStream(fs, aes.CreateEncryptor(), CryptoStreamMode.Write, true);
new BinaryFormatter().Serialize(cs, handler.CookieContainer);
}
}
HttpClientHandler
прекрасно справляется с этой задачей без постороннего вмешательства. Да и самCookieContainer
не так прост, как казалось бы.