2012-03-21 39 views
5

我正在編寫一個內容管理系統,用戶可以在該應用程序內部創建多個網站。每個站點都可以進行認證。我想弄清楚如何爲應用程序提供多個身份驗證Cookie,而無需將每個cookie都添加到web.config中。我需要在應用程序啓動時以編程方式創建它們。這可能嗎?如何以編程方式爲單個應用程序提供多個身份驗證Cookie

Ex。

SecureApp:http://localhost/CTMS - 需要進行認證的更新站點

CustomSite:http://localhost/CTMS/Custom1 - 從SecureApp

需要進行認證的獨立但願這是有道理的。

回答

8

你可以做到這一點 -

FormsAuthenticationTicket _ticket = new FormsAuthenticationTicket(_version, _name, _issueDate, _expirationDate, _isPersistent, _userData, _cookiePath); 

string _encryptedTicket = FormsAuthentication.Encrypt(_ticket); 

HttpCookie _cookie = new HttpCookie("customticket", _encryptedTicket); 

HttpContext.Current.Response.Cookies.Add(_cookie); 

然後你就可以編寫代碼來檢查傳入的請求,看看他們是否有這個Cookie -

HttpCookie _cookie = HttpContext.Current.Request.Cookies["customticket"]; 

if(_cookie){ 

_encryptedTicket = _cookie.Value; 
FormsAuthenticationTicket _ticket = FormsAuthentication.Decrypt(_encryptedTicket); 

    if(!_ticket.Expired) { 
     IIdentity _identity = new FormsIdentity(_ticket); 
     IPrincipal _principal = new GenericPrincipal(_identity, new string[0]); //Identity plus string of roles. 
    } 
} 
else{ 
//dostuff 
} 
+0

寫的問題後,這是我最後的辦法一起去。謝謝! – 2012-03-22 18:53:59

+0

極好的解決方案。我已經在我們的MVC 5應用程序中採用了這一點。 – Tommassiov 2015-02-25 11:27:26

相關問題