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

时间:2013-09-08 11:16:37

标签: asp.net-mvc cookies

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

<authentication mode="Forms">
  <forms name="myName" loginUrl="~/Account/Login" defaultUrl="~/Admin/admin" cookieless="UseCookies" slidingExpiration="true"  timeout="40320"/>
</authentication>

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

2 个答案:

答案 0 :(得分:4)

我在很长一段时间里一直在努力使用Cookie。这是一次非常棒的学习经历。

所以想分享我找到的可能方式&amp;发现:有几个HACK修改表单身份验证Cookie名称:

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

  2. 感谢ILSpy允许我在FormsAuthentication类中查看,并且非常感谢Reflection允许我修改类的私有字段。我使用以下代码在运行时使用以下一小段代码修改cookie名称,这就像一个魅力!

  3.     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);
        }
    

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

答案 1 :(得分:1)

你不能在代码中这样做;属性FormsAuthentication.FormsCookieName是readonly。我会在web.config中使用以下配置:

<authentication mode="Forms">
  <forms configSource="forms.config" />
</authentication>

然后为应用程序的每个实例提供自己的forms.config

<forms name="CookieNameForThisInstance" />