我正在使用 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视图中)访问这些声明。
我尝试了本教程中列出的方法:
例如,在我的控制器代码中,我尝试获取传递到声明中的值,但是user.Claims等于null。
var ctx = HttpContext.GetOwinContext();
ClaimsPrincipal user = ctx.Authentication.User;
IEnumerable<Claim> claims = user.Claims;
也许我在这里漏掉了什么。
更新
根据Darin的回答,我添加了他的代码,但我仍然没有看到访问Claims的权限。请参见下面的屏幕截图,显示当我悬停在identity.Claims上时看到的内容。