Jez*_*Jez 6 c# asp.net asp.net-core asp.net-core-3.0
我想手动解密.AspNetCore.Identity.ApplicationASP.NET Core 3.0.0 存储的 cookie,以准确查看它包含哪些信息。我知道 Microsoft 在 ASP.NET Core 2.2 和 3.0 之间显着改变了此操作的方式,因此现在 3.0 已全面发布,我想知道:如何在应用程序代码中手动解密此 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6188 次 |
| 最近记录: |