簡體   English   中英

我可以在asp.net中動態更改FormsAuthentication cookie名稱嗎?

[英]Can I change the FormsAuthentication cookie name in asp.net dynamically?

我想動態設置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。

幾天來,我一直在與Cookies斗爭。 這是一個很棒的學習經歷。

因此,我想分享我發現和發現的可能方法:有幾種HACK可以修改表單身份驗證Cookie名稱:

  1. 您可以在Global.asax的Application_Start事件中的Web.Config文件的Authenticaiton部分下自動修改cookie名稱。 感謝Ron分享此內容 但是我不能保證其身份將用於運行應用程序域的用戶具有足夠的特權來修改或不修改磁盤上的文件。 因此,我需要一個臨時的解決方案,因此我設計了以下方案。

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

建議,需要漏洞,因為這是我在該論壇上的第一個答案。

您無法在代碼中執行此操作; 屬性FormsAuthentication.FormsCookieName為只讀。 我將在web.config使用以下配置:

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

然后為應用程序的每個實例提供自己的forms.config

<forms name="CookieNameForThisInstance" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM