2015-04-14 28 views
0

我有幾個客戶,誰是子域區分的多租戶應用程序:限制驗證和會話cookie的子域在ASP.NET MVC5

client1.mydomain.com 
client2.mydomain.com 
etc 

我使用窗體身份驗證和ASP。 NET Auth &客戶端上的會話cookie是爲子域設置的,例如client1.mydomain.com。這意味着如果我瀏覽到client2.mydomain.com,那麼我沒有登錄並且瀏覽器不會發布client1 cookie。這是應該的。

但是,我們的安全測試已經發現,您可以從client1獲取cookie值,並使用這些值爲client2創建cookie(我們已經在firebug中完成了這項工作)。 ASP.NET接受這些cookie並認爲你在client2上被授權。

如何配置ASP.NET,使其不會發生?

web.config中的forms元素允許您設置域,但我不能使用它,因爲我有一個多租戶應用程序。我設置的Cookie與

FormsAuthentication.SetAuthCookie(userName, false); 

但我沒有看到爲什麼要限制這個子域。

回答

2

您應該將域名添加到cookie的用戶數據。要做到這一點,你必須切換到另一個餅乾API:

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
    ... other parameters ..., domain); 

HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName); 

cookie.Value = FormsAuthentication.Encrypt(ticket); 

Response.SetCookie(cookie); 

然後,在全局應用程序類有一個事件處理程序觸發後的身份被確定的請求。在處理程序,驗證cookie中的域名等於當前請求的域名:

public void Application_PostAuthorizeRequest(object sender, EventArgs e) 
{ 
    HttpApplication app = sender as HttpApplication; 
    HttpContext ctx = app.Context; 

    if (ctx.User.Identity.IsAuthenticated) 
    { 
     // current domain 
     string currentDomain = ctx.Request.Url.... // get the domain 

     // domain from cookie 
     FormsIdentity id = (FormsIdentity)ctx.User.Identity; 
     FormsAuthenticationTicket ticket = id.Ticket; 

     string cookieDomain = ticket.UserData; 

     if (currentDomain != cookieDomain) 
      throw new Exception("break the execution of the current request"); 

     ... 

如果cookie發出了當前域或者說有人試圖之間重複使用cookies,這些檢查將驗證不同的領域。