如何在Azure网站上设置machineKey

Mr.*_*ble 28 asp.net authentication azure machinekey

我正在运行Azure网站.每当我部署时,每个人都会因为machineKey更改而退出.

我指定machineKeyweb.config,但是这并没有解决问题.我相信这是因为Azure会自动覆盖machineKey [1].

我在这里找到了几个类似的问题,但答案链接到死链接.

那么,解决方案是什么?当然,无论Azure上的部署如何,都有办法让用户登录.

hai*_*770 20

尝试重置机器密钥配置部分Application_Start:

protected void Application_Start()
{
    // ...

    var mksType = typeof(MachineKeySection);
    var mksSection = ConfigurationManager.GetSection("system.web/machineKey") as MachineKeySection;
    var resetMethod = mksType.GetMethod("Reset", BindingFlags.NonPublic | BindingFlags.Instance);

    var newConfig = new MachineKeySection();
    newConfig.ApplicationName = mksSection.ApplicationName;
    newConfig.CompatibilityMode = mksSection.CompatibilityMode;
    newConfig.DataProtectorType = mksSection.DataProtectorType;
    newConfig.Validation = mksSection.Validation;

    newConfig.ValidationKey = ConfigurationManager.AppSettings["MK_ValidationKey"];
    newConfig.DecryptionKey = ConfigurationManager.AppSettings["MK_DecryptionKey"];
    newConfig.Decryption = ConfigurationManager.AppSettings["MK_Decryption"]; // default: AES
    newConfig.ValidationAlgorithm = ConfigurationManager.AppSettings["MK_ValidationAlgorithm"]; // default: SHA1

    resetMethod.Invoke(mksSection, new object[] { newConfig });
}
Run Code Online (Sandbox Code Playgroud)

以上假设您在以下<appSettings>部分中设置了适当的值:

<appSettings>
  <add key="MK_ValidationKey" value="...08EB13BEC0E42B3F0F06B2C319B..." />
  <add key="MK_DecryptionKey" value="...BB72FCE34A7B913DFC414E86BB5..." />
  <add key="MK_Decryption" value="AES" />
  <add key="MK_ValidationAlgorithm" value="SHA1" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)

但您可以从任何您喜欢的配置源加载实际值.


Aka*_*ava 1

如果 Azure 正在重写您的 machineKey,您对此无能为力,因为它是其基础设施的一部分。然而,还有其他方法。

覆盖表单验证

这应该不难,因为您可以轻松查找 FormsAuthentication 的源代码并创建您自己的逻辑,并将 MachineKey 替换为存储在 web.config 或数据库中的您自己的密钥。

自定义身份验证过滤器

最简单的方法是创建一个过滤器并在过滤器中检查、验证、加密和解密 cookie。您需要在 OnAuthorization 方法上执行此操作,并创建 IPrincipal 的新实例,如果解密成功,则将 IsAuthenticated 设置为 true。

开放认证

  1. 启用 OAuth 并创建 OAuthProvider。但是,您需要在您控制的服务器上托管 OAuthProvider,因为这需要 machineKey 工作。
  2. 启用第三方 OAuth,如果您启用 Google、Facebook 等 OAuth,这将很容易,因为用户将被重定向到 OAuth 提供商,他们将继续自动登录并建立新会话。