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

时间:2019-10-13 11:06:21

标签: c# asp.net asp.net-core asp.net-core-3.0

我想手动解密由ASP.NET Core 3.0.0存储的.AspNetCore.Identity.Application cookie,以查看其确切包含的信息。我了解微软已经相当大地改变了ASP.NET Core 2.2和3.0之间的操作方式,因此,既然3.0已发布到一般可用性,我想知道:如何在应用程序代码中手动解密此cookie在Core 3.0中?

1 个答案:

答案 0 :(得分:1)

这是基于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);
    }
}