RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题

全部问题

Martin Hope
aepot
Asked: 2020-09-14 18:35:48 +0000 UTC

在 HttpClient 中使用 Cookie 进行授权解析

  • 11

我一直想知道如何让HttpClientcookies像浏览器一样工作,然后在退出应用程序时保存,重启后继续使用。然后,最后,它找到了我,我做到了。

让它HttpClient像这样工作:

检查代码

public static class HttpManager
{
    private static readonly HttpClientHandler handler = new HttpClientHandler()
    {
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli,
        AllowAutoRedirect = true
    };

    private static readonly HttpClient client = new HttpClient(handler)
    {
        DefaultRequestVersion = new Version(2, 0)
    };

    static HttpManager()
    {
        client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0");
        client.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br");
    }

    // 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;
    }
}

Cookie 被序列化为 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 бронзовых знаков

应用重启时输出到控制台,自动使用cookies进行授权

aepot
ваша репутация: 4,904
2 золотых знака
5 серебряных знаков
25 бронзовых знаков

无需检查可重现的示例,我知道它不考虑密码错误情况或帐户不支持密码登录。

顺便一提!为此,您需要在 StackExchange 帐户的安全设置中启用登录名和密码。

请看课程代码HttpManager,有什么需要改进或做不同的吗?我以前没有使用过 Cookie。


更新- 使用BinaryFormatter

在@ヒミコ的建议下,我尝试了一个使用. 它也有效。好处 - 现在您不需要额外的方法来提取 cookie,但它会“按原样”保存。我还没有弄清楚哪个更好,但微软斥责它不安全。BinaryFormatterCookieContainer BinaryFormatter

BinaryFormatter是不安全的,不能保证安全。有关详细信息,请参阅BinaryFormatter 安全指南。

public static class HttpManager
{
    private static readonly HttpClientHandler handler = new HttpClientHandler()
    {
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli,
        AllowAutoRedirect = true
    };

    private static readonly HttpClient client = new HttpClient(handler)
    {
        DefaultRequestVersion = new Version(2, 0)
    };

    static HttpManager()
    {
        client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0");
        client.DefaultRequestHeaders.AcceptEncoding.ParseAdd("gzip, deflate, br");
    }

    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);
    }
}
c#
  • 1 个回答
  • 10 Views
Martin Hope
Burg
Asked: 2020-07-30 23:22:38 +0000 UTC

什么时候使用 Set a when WeakSet

  • 11

何时使用 Set a vs. WeakSet,有什么区别,哪个更好,为什么?

var arr = [1, 2, 3, 4, 5]; 

和

var set = new Set([1, 2, 3, 4, 5]); 

和

var weak_set = new WeakSet([1, 2, 3, 4, 5]);

文档已经写好,但不清楚应该在哪里使用以及为什么。

javascript
  • 2 个回答
  • 10 Views
Martin Hope
LeopardL GD
Asked: 2020-06-15 00:38:02 +0000 UTC

更改我自己编写的操作系统的位数?

  • 11

我写操作系统。由于我缺乏经验,我只能对 32 位(我的操作系统是 32 位)执行此操作,但我想将其设为 64 位。

我应该怎么办?

这是我专门用于汇编程序的内核代码:

.set MAGIC, 0x1badb002
.set FLAGS, (1<<0 | 1<<1)
.set CHECKSUM, -(MAGIC + FLAGS)

.section .multiboot
  .long MAGIC
  .long FLAGS
  .long CHECKSUM

.section .text
.extern kernelMain
.global loader

loader:
    mov $kernel_stack, %esp
    push %eax
    push %ebx
    call kernelMain

_stop:
    cli
    hlt
    jmp _stop

.section .bss
.space 2*1024*1024; # 2 megabytes of space
kernel_stack:

当然,它还没有完成,但它已经接近了。还有更多信息:我用Ubuntu
编译我的 GNU 汇编器代码;asC++ 代码使用g++.

如果您发现重复,请发布链接。

c++
  • 1 个回答
  • 10 Views
Martin Hope
Houck z
Asked: 2020-05-15 20:59:23 +0000 UTC

如何制作这样的径向透明切口?

  • 11

在此处输入图像描述

请帮我从这个金色圆圈的底部制作一个透明的切口,也许可以通过剪辑路径或其他方式完成?

html
  • 4 个回答
  • 10 Views
Martin Hope
Monkey Mutant
Asked: 2020-04-06 03:52:25 +0000 UTC

有没有可能用纯css来实现如此平滑的图像过渡效果?

  • 11

看到一个网站,效果很有意思:https ://travelshift.com/

在右上角有一个带箭头的圆形按钮,如果你点击它,想要的效果开始了,我所有的尝试都失败了,没有代码。

也许有人不会看到它,这个皮肤链接到 Dropbox 中的视频:视频

单击鼠标按钮后效果本身开始..

是否有可能在 css 上至少获得部分副本?

不需要 javascript 着色器答案

css3
  • 2 个回答
  • 10 Views
上一页
下一页

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5