gpt4 book ai didi

security - 如何手动解密 ASP.NET Core 身份验证 cookie?

转载 作者:行者123 更新时间:2023-12-03 09:56:46 25 4
gpt4 key购买 nike

让我们考虑一个众所周知的 ASP.NET Core 场景。首先我们添加中间件:

public void Configure(IApplicationBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookie",
CookieName = "MyCookie",
LoginPath = new PathString("/Home/Login/"),
AccessDeniedPath = new PathString("/Home/AccessDenied/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});
//...
}
然后序列化一个主体:
await HttpContext.Authentication.SignInAsync("MyCookie", principal);
在这两个调用之后,一个加密的 cookie 将被存储在客户端。您可以在任何浏览器开发工具中看到 cookie(在我的情况下是分 block 的):
chunked encrypted cookie generated by ASP.NET
使用来自应用程序代码的 cookie 不是问题(也不是问题)。
我的问题是: 如何解密应用程序外的cookie ?我想这需要一个私钥,如何获得它?
我查了 docs只找到常用词:

This will create an encrypted cookie and add it to the currentresponse. The AuthenticationScheme specified during configuration mustalso be used when calling SignInAsync.

Under the covers the encryption used is ASP.NET's Data Protectionsystem. If you are hosting on multiple machines, load balancing orusing a web farm then you will need to configure data protection touse the same key ring and application identifier.


那么,是否可以解密身份验证 cookie,如果可以,如何解密?
更新#1:
基于 Ron C great answer and comments ,我最终得到了代码:
public class Startup
{
//constructor is omitted...

public void ConfigureServices(IServiceCollection services)
{
services.AddDataProtection().PersistKeysToFileSystem(
new DirectoryInfo(@"C:\temp-keys\"));

services.AddMvc();
}

public void Configure(IApplicationBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
AuthenticationScheme = "MyCookie",
CookieName = "MyCookie",
LoginPath = new PathString("/Home/Index/"),
AccessDeniedPath = new PathString("/Home/AccessDenied/"),
AutomaticAuthenticate = true,
AutomaticChallenge = true
});

app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
}

public class HomeController : Controller
{
public async Task<IActionResult> Index()
{
await HttpContext.Authentication.SignInAsync("MyCookie", new ClaimsPrincipal());

return View();
}

public IActionResult DecryptCookie()
{
var provider = DataProtectionProvider.Create(new DirectoryInfo(@"C:\temp-keys\"));

string cookieValue = HttpContext.Request.Cookies["MyCookie"];

var dataProtector = provider.CreateProtector(
typeof(CookieAuthenticationMiddleware).FullName, "MyCookie", "v2");

UTF8Encoding specialUtf8Encoding = new UTF8Encoding(false, true);
byte[] protectedBytes = Base64UrlTextEncoder.Decode(cookieValue);
byte[] plainBytes = dataProtector.Unprotect(protectedBytes);
string plainText = specialUtf8Encoding.GetString(plainBytes);

return Content(plainText);
}
}
不幸的是,这段代码总是在 Unprotect 上产生异常。方法调用:

CryptographicException in Microsoft.AspNetCore.DataProtection.dll:Additional information: The payload was invalid.


我在几台机器上测试了这段代码的不同变体,但没有得到肯定的结果。可能我犯了一个错误,但在哪里?
更新#2:我的错误是 DataProtectionProvider尚未在 UseCookieAuthentication 中设置.再次感谢@RonC。

最佳答案

在 ASP.NET Core 应用程序中,您可以使用 CookieAuthenticationOptions.TicketDataFormat.Unprotect(cookieValue) .
在这里,我写了一个简单的静态(!)方法:

public static AuthenticationTicket DecryptAuthCookie(HttpContext httpContext)
{
// ONE - grab the CookieAuthenticationOptions instance
var opt = httpContext.RequestServices
.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>()
.Get(CookieAuthenticationDefaults.AuthenticationScheme); //or use .Get("Cookies")

// TWO - Get the encrypted cookie value
var cookie = opt.CookieManager.GetRequestCookie(httpContext, opt.Cookie.Name);

// THREE - decrypt it
return opt.TicketDataFormat.Unprotect(cookie);
}
在 .NET 5 和 .NET 6 下工作正常。
我添加了这个答案以供引用,因为如果您搜索如何手动解密 ASP.NET auth cookie,每个搜索引擎都会弹出这个问题。

关于security - 如何手动解密 ASP.NET Core 身份验证 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42842511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com