2013-12-14 21 views
27

我創建了一個全新的Web應用程序,例如「WebApplication1」 - WebForms的身份驗證設置爲個人用戶帳戶。我不會將一行代碼添加到自動生成的代碼模板中。我運行應用程序並註冊一個用戶「User1」並登錄 - 工作正常。爲什麼來自一個站點的ASP.NET身份登錄與同一臺計算機上的不同網站共享?

現在我創建另一個Web應用程序「WebApplication2」 - 相同的WebForms與設置爲個人用戶帳戶的身份驗證。再次沒有代碼,我運行該應用程序。現在我創建另一個用戶說「用戶2」 - 工作正常。

當兩個應用程序同時運行時,問題就開始了。 如果我以「User1」的身份登錄到第一個站點,當它甚至沒有註冊「User1」時,它會自動將第二個站點的Context.User.Identity設置爲「webApplication2」爲「User1」,反之亦然從一個站點註銷另一個站點註銷。

如何分享Context.User.Identity?

的代碼是一樣的 -

public static void SignIn(UserManager manager, ApplicationUser user, bool isPersistent){ 

     IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication; 
     authenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie); 

     var identity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie); 
     authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity); 
    } 

我真的很想念在ASP.Net身份是如何工作的,請幫我出一些基本知識。

在此先感謝。

+0

很好的問題及以下優良接受的答案。建議重命名問題的標題更多的東西「的問題十歲上下」,像「爲什麼從一個站點ASP.NET身份登錄得到相同的機器上不同的網站共享?」 (或類似的東西...) – Funka

+0

@Funka - 根據您的建議更改了問題。 –

回答

47

如果您的服務器配置爲使用Cookie身份驗證,服務器將向瀏覽器返回一個包含加密和簽名的有關該用戶的聲明的cookie。

此cookie默認名爲:.AspNet.ApplicationCookie。

此cookie將存儲在您的瀏覽器中,直到它過期(默認14天和滑動過期)或您明確註銷刪除cookie。

如果您打開另一個具有相同瀏覽器類型的選項卡或窗口,則在您登錄後,它也會具有相同的cookie,並在向兩個網站中的任一個發送請求時傳遞它。

如果兩個站點都配置爲查找相同的cookie名稱,他們都會看到它,並且能夠解密身份驗證cookie,因爲它們共享同一臺計算機,因此服務器使用的計算機密鑰加密/解密並簽署cookie。 cookie中沒有任何內容告訴它屬於同一服務器中的哪個站點,因此存儲在您的WebApplication1網站中的「User1」聲明將被視爲在WebApplication2上進行身份驗證。 如果傳入請求中有一個有效的cookie,OWIN認證中間件將不檢查數據庫。它將簡單地使用cookie中提供的加密聲明(用戶名,可能的角色和其他)。

如果你在你的兩個web應用在不同的CookieName設置成他們不會使用相同的身份驗證cookie,因此用戶在一個網站身份驗證將不會在其他認證。

可以的CookieName設置成你的Startup.Auth.cs這樣的:

public partial class Startup 
{ 
    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 
    public void ConfigureAuth(IAppBuilder app) 
    { 
     // Enable the application to use a cookie to store information for the signed in user 
     app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
      LoginPath = new PathString("/Account/Login"), 
      CookieName = "MyCookieName", 

     }); 
    } 
} 
+0

現在絕對有意義。謝謝! –

相關問題