【发布时间】:2014-02-19 17:06:16
【问题描述】:
我正在使用 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 的回答,我添加了他的代码,但我仍然看不到对声明的访问权限。请参阅下面的屏幕截图,显示我将鼠标悬停在身份上时看到的内容。声明。
【问题讨论】:
-
你能确认cookie是浏览器发回的吗?也许您的安全设置需要 SSL?
-
@leastprivilege 谢谢,我现在就调查一下。我在 Stackoverflow 上发现了这个问题,stackoverflow.com/questions/20319118/… 这与我遇到的问题完全相同,但不幸的是没有答案:(
-
你的 OWIN 组件是如何初始化的?
-
我最近遇到了这样的问题;我希望这个解决方案有所帮助:stackoverflow.com/questions/34537475/…
标签: asp.net asp.net-mvc authentication asp.net-mvc-5 claims-based-identity