调用提供的cookie:
await HttpContext.Authentication.SignInAsync("MyCookieMiddlewareInstance", principal);
以加密状态存储。如何获取加密 key ?
重要:这个问题源 self 的 original question关于cookie解密。感谢Ron C以及他出色的回答。
最佳答案
获取 key
默认情况下,.net core 框架会竭尽全力保持 key 的私密性,并帮助开发人员避免处理 key 的任何需要。这很好,因为开发人员很难保证 key 的安全。
也就是说,通过更改配置,您可以轻松访问 key 。
将以下代码行添加到 Startup.cs
文件的 ConfigureServices
方法中。如果您使用 use session,请将其添加到 AddSession
行下方:
services.AddDataProtection().PersistKeysToFileSystem(new DirectoryInfo(keyDirPath));
并将 keyDirPath
设置为您想要存储 key 的目录的操作系统绝对路径。该目录不需要已经存在,因为系统将动态创建它。就我而言,我将目录设置为名为 Keys 的文件夹。这是运行代码一次后目录的样子,它包含一个关键文件:
该 key 文件的内容未加密,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<key id="677f1115-644a-4b11-b045-0c3c51675ef1" version="1">
<creationDate>2017-03-17T12:21:10.8909291Z</creationDate>
<activationDate>2017-03-17T12:21:10.8419262Z</activationDate>
<expirationDate>2017-06-15T12:21:10.8419262Z</expirationDate>
<descriptor deserializerType="Microsoft.AspNetCore.DataProtection.AuthenticatedEncryption.ConfigurationModel.AuthenticatedEncryptorDescriptorDeserializer, Microsoft.AspNetCore.DataProtection, Version=1.1.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60">
<descriptor>
<encryption algorithm="AES_256_CBC" />
<validation algorithm="HMACSHA256" />
<masterKey p4:requiresEncryption="true" xmlns:p4="http://schemas.asp.net/2015/03/dataProtection">
<!-- Warning: the key below is in an unencrypted form. -->
<value>BMJ6EY5MbcR0vaXhCbHggQcVsuYc6MnMtQpQm0qL647UBVx0YDbZufqQ+2/XuahFfIY2fJ6BIlOl+LYODnLbrA==</value>
</masterKey>
</descriptor>
</descriptor>
</key>
警告:您不应该将 key 以完全不 protected 状态放置在名为“keys”的文件夹中。这样做不是安全最佳实践。但如果您想了解安全系统,这是一个有用的练习。
您可以在此处了解有关数据保护服务的更多信息:https://learn.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview
关于security - 如何获取 Asp.Net Core 加密 key 的访问权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42913017/