【问题标题】:How to decrypt .AspNetCore.Identity.Application cookie in ASP.NET Core 3.0?如何在 ASP.NET Core 3.0 中解密 .AspNetCore.Identity.Application cookie?
【发布时间】:2019-10-15 01:14:20
【问题描述】:

我想手动解密由 ASP.NET Core 3.0.0 存储的 .AspNetCore.Identity.Application cookie,以查看它包含的确切信息。我了解 Microsoft 在 ASP.NET Core 2.2 和 3.0 之间的操作方式发生了很大变化,因此现在 3.0 已发布到普遍可用状态,我想知道:如何在我的应用程序代码中手动解密此 cookie在 Core 3.0 中?

【问题讨论】:

    标签: c# asp.net asp.net-core asp.net-core-3.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);
        }
    }
    

    【讨论】:

    • Startup 下的解密代码不是很有帮助,因为关键是解密一个在启动期间不存在的 cookie。此外,_storedOption 为 null,除非添加必需的配置(例如,将 ``CookieAuthenticationDefaults.AuthenticationScheme` 传递给 services.AddAuthentication)。另外,option =&gt; ... 应该是 options =&gt; ...
    猜你喜欢
    • 1970-01-01
    • 2017-08-08
    • 2021-04-11
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-01
    相关资源
    最近更新 更多