簡體   English   中英

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

[英]How to decrypt .AspNetCore.Identity.Application cookie in ASP.NET Core 3.0?

我想手動解密由 ASP.NET Core 3.0.0 存儲的.AspNetCore.Identity.Application cookie,以查看它包含的確切信息。 我知道微軟在 ASP.NET Core 2.2 和 3.0 之間已經大大改變了這是如何完成的,所以現在 3.0 已經發布到普遍可用,我想知道:如何在 Core 的應用程序代碼中手動解密這個 cookie 3.0?

這是基於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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM