让我们考虑一个常见的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
});
//...
}
Run Code Online (Sandbox Code Playgroud)
然后序列化一个委托人:
await HttpContext.Authentication.SignInAsync("MyCookie", principal);
Run Code Online (Sandbox Code Playgroud)
在这两次调用之后,加密的cookie将存储在客户端.你可以在任何浏览器devtools中看到cookie(在我的例子中它是分块的):
使用应用程序代码中的cookie不是问题(而不是问题).
我的问题是:如何在应用程序外解密cookie?我想这需要一个私钥,如何获得它?
我检查了文档,发现只有常用词:
这将创建一个加密的cookie并将其添加到当前响应中.调用SignInAsync时,还必须使用配置期间指定的AuthenticationScheme.
在封面下,使用的加密是ASP.NET的数据保护系统.如果您在多台计算机上进行托管,负载平衡或使用Web场,则需要配置数据保护以使用相同的密钥环和应用程序标识符.
那么,是否可以解密身份验证cookie,如果是,如何解密?
更新#1: 根据Ron C 的回答和评论,我最终得到了代码:
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 = …Run Code Online (Sandbox Code Playgroud) security authentication cookies asp.net-core-mvc asp.net-core