2015-10-06 42 views
0

有沒有一種方法來驗證會話而不創建MVC 5身份的ApplicationUser?MVC 5 Identity(v2)身份驗證而不創建應用程序用戶

由於各種原因,我最終使用了雙層認證系統。我將自定義數據庫中的「用戶」對象解析爲會話,並在整個站點的各個位置解析此對象的存在是如何確定用戶的登錄狀態。

我在網站的各個地方使用Identity用戶的東西(例如聲明,登錄等)。但在這個特定的實例中,我需要登錄匿名身份用戶並解析請求會話的任何用戶對象。那麼我如何創建一個Identity V2的匿名身份驗證會話?

回答

1

在Identity中,您不需要擁有用戶對象進行身份驗證。您可以即時創建一些聲明並使用它們進行身份驗證。考慮一個簡單的例子:

[HttpPost] 
public ActionResult AnonymousLogin() 
{ 
    var ident = new ClaimsIdentity(
     new[] 
     { 
      // adding following 2 claim just for supporting default antiforgery provider 
      new Claim(ClaimTypes.NameIdentifier, "AnonymousUserID"), 
      new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"), 

      new Claim(ClaimTypes.Name, "AnonymousUserID"), 
     }, 
     DefaultAuthenticationTypes.ApplicationCookie); 

    HttpContext.GetOwinContext().Authentication.SignIn(
     new AuthenticationProperties { IsPersistent = false }, ident); 
    return RedirectToAction("MyAction"); // auth succeed 
} 

現在你已經驗證的匿名用戶就像一個真正的用戶:

[Authorize] 
public ActionResult MyAction() 
{ 
    // all authorized users could use this method don't matter how have been authenticated 
    // you have access current user principal 
    var username=HttpContext.User.Identity.Name; 
} 
+0

真棒,我需要知道到底是什麼。我無法擺脫會話中的用戶對象,因爲我正在使用此網站的網站上工作,但我將我的方法分層以將此對象與Identity分開。非常感謝,這的確有幫助。 –