Asp.net
MVC 5 訪問聲明身份使用者數據
我正在使用Entity Framework 5 Database First方法開發一個****MVC 5 Web 應用程序。我正在使用OWIN對使用者進行身份驗證。下面顯示了我的帳戶控制器中的登錄方法。
public ActionResult Login(LoginViewModel model, string returnUrl) { if (ModelState.IsValid) { var user = _AccountService.VerifyPassword(model.UserName, model.Password, false); if (user != null) { var identity = new ClaimsIdentity(new[] { new Claim(ClaimTypes.Name, model.UserName), }, DefaultAuthenticationTypes.ApplicationCookie, ClaimTypes.Name, ClaimTypes.Role); identity.AddClaim(new Claim(ClaimTypes.Role, "guest")); identity.AddClaim(new Claim(ClaimTypes.GivenName, "A Person")); identity.AddClaim(new Claim(ClaimTypes.Sid, user.userID)); //OK to store userID here? AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = model.RememberMe }, identity); return RedirectToAction("Index", "MyDashboard"); } else { ModelState.AddModelError("", "Invalid username or password."); } } // If we got this far, something failed, redisplay form return View(model); }如您所見,我正在創建一個ClaimsIdentity並向其添加多個聲明,然後使用AuthenticationManager將其傳遞給OWIN以執行登錄。
我遇到的問題是我不確定如何在我的應用程序的其餘部分(無論是在控制器中還是在 Razor 視圖中)訪問聲明。
我嘗試過本教程中列出的方法
<http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/>
例如,我在我的控制器程式碼中嘗試了這個,試圖訪問傳遞給聲明的值,但是,user.Claims 等於 null
var ctx = HttpContext.GetOwinContext(); ClaimsPrincipal user = ctx.Authentication.User; IEnumerable<Claim> claims = user.Claims;也許我在這裡遺漏了一些東西。
更新
根據達林的回答,我添加了他的程式碼,但我仍然看不到對聲明的訪問。請參閱下面的螢幕截圖,顯示我將滑鼠懸停在 identity.Claims 上時看到的內容。
嘗試這個:
[Authorize] public ActionResult SomeAction() { var identity = (ClaimsIdentity)User.Identity; IEnumerable<Claim> claims = identity.Claims; ... }
