如何在ASP.NET Core 3.0中解密.AspNetCore.Identity.Application Cookie?

6

我想手动解密ASP.NET Core 3.0.0存储的.AspNetCore.Identity.Application cookie,以查看其中包含的信息。我知道微软已经在ASP.NET Core 2.2和 3.0之间相当大地改变了这个过程,所以现在3.0已经发布到普通可用性,我想知道:如何在我的应用程序代码中手动解密这个cookie?

1个回答

6

这就是如何根据CookieAuthenticationHandler解密Cookie的方法。

public class Startup
{
    private CookieAuthenticationOptions _storedOption;


    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication()
            .AddCookie(option =>
            {
                _storedOption = option;
            });
    }

    public AuthenticationTicket Decrypt(HttpContext context, string cookie)
    {
        AuthenticationTicket ticket = _storedOption.TicketDataFormat.Unprotect(cookie, GetTlsTokenBinding(context));
        return ticket;
    }

    public string DecryptRaw(HttpContext context, string cookie)
    {
        IDataProtectionProvider dataProtectionProvider = _storedOption.DataProtectionProvider;

        IDataProtector protector = dataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", "Identity.Application", "v2");

        string purpose = GetTlsTokenBinding(context);

        if (!string.IsNullOrEmpty(purpose))
        {
            protector = protector.CreateProtector(purpose);
        }

        var protectedData = Base64UrlTextEncoder.Decode(cookie);

        byte[] userData = protector.Unprotect(protectedData);

        var rawText = Encoding.UTF8.GetString(userData);

        return rawText;
    }

    private string GetTlsTokenBinding(HttpContext context)
    {
        var binding = context.Features.Get<ITlsTokenBindingFeature>()?.GetProvidedTokenBindingId();
        return binding == null ? null : Convert.ToBase64String(binding);
    }
}

将解密代码放在“启动”下面并不是很有帮助,因为要解密的cookie在启动期间不存在。此外,除非添加所需的配置(例如将“CookieAuthenticationDefaults.AuthenticationScheme”传递给“services.AddAuthentication”),否则“_storedOption”为空。另外,“option => ...”应该改为“options => ...”。 - OfirD

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接