我可以动态更改 asp.net 中的 FormsAuthentication cookie 名称吗?

a.b*_*a.b 2 cookies asp.net-mvc

我想动态设置 FormsAuthentication cookie 名称,例如 guid。我怎样才能做到这一点。我已经可以在 web.config 中将其更改为我想要的任何内容。我只是无法用代码和动态方式做到这一点。请帮忙。

<authentication mode="Forms">
  <forms name="myName" loginUrl="~/Account/Login" defaultUrl="~/Admin/admin" cookieless="UseCookies" slidingExpiration="true"  timeout="40320"/>
</authentication>
Run Code Online (Sandbox Code Playgroud)

我想这样做的原因是,我的应用程序在同一主机上有多个实例,并且我不希望它们覆盖彼此的 cookie。

小智 5

这几天我一直在与 Cookie 作斗争。这是一次很棒的学习经历。

所以想分享我发现和发现的可能方法:有几种修改表单身份验证 Cookie 名称的 HACK:

  1. 您可以在 Global.asax 中的 Application_Start 事件中的 Web.Config 文件的 Authenticaiton 部分下自动修改 cookie 名称。感谢罗恩分享这个。但我无法保证其身份将用于运行应用程序域的用户是否有足够的权限来修改磁盘上的文件。因此我需要一个临时解决方案,所以我设计了以下方案。

  2. 感谢 ILSpy 让我看到 FormsAuthentication 类的内部,也非常感谢 Reflection 让我修改类的私有字段。我使用下面的代码在运行时修改 cookie 名称,并使用下面的一小段代码,这就像一个魅力!


    protected void Application_Start(Object sender, EventArgs e)
    {
        // This will enforce that FormsAuthentication class is loaded from configuration settings for the application.
        FormsAuthentication.Initialize();

        // The new cookie name whatever you need can go here, I needed some value from my application setting to be prefixed so I used it.
        string newCookieName = string.Format("{0}.ASPXAUTH", ConfigurationManager.AppSettings["SomeSettingThatIsUniquetoSite"]);

        // Modifying underlying baking field that points to FormsAuthentication.FormsCookieName         
        Type type = typeof(FormsAuthentication);
        System.Reflection.FieldInfo field = type.GetField("_FormsName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
        field.SetValue(null, newCookieName);
    }
Run Code Online (Sandbox Code Playgroud)

建议,漏洞,因为这是我在这个论坛上的第一个答案。