MVC 5访问索赔身份的用户数据 [英] MVC 5 Access Claims Identity User Data
问题描述
我在开发的 MVC 5 使用Web应用程序的实体框架5数据库首页的办法。我使用的 OWIN 作为用户的身份验证。下面显示了我的帐户Controller中我的登录方式。
I am developing an MVC 5 web application using Entity Framework 5 Database First approach. I am using OWIN for the authentication of Users. Below shows my Login method within my Account Controller.
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 并增加几个声称它,然后将它传递给 OWIN 使用的AuthenticationManager 以在执行迹象。
As you can see I'm creating a ClaimsIdentity and adding several claims to it, then passing it to OWIN using the AuthenticationManager to perform the sign in.
我遇到的问题是,我不知道如何访问这些索赔我的应用程序的其余部分,无论是在控制器或剃刀视图。
我曾试图在本教程中列出的方法
I had tried the approach listed in this tutorial
<一个href=\"http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/\">http://brockallen.com/2013/10/24/a-primer-on-owin-cookie-authentication-middleware-for-the-asp-net-developer/
例如,我试图以访问传递到索赔值尝试这在我的控制器code,然而,user.Claims等于空
For example, I tried this in my Controller code in an attempt to get access to the values passed into the Claims, however, the user.Claims is equal to null
var ctx = HttpContext.GetOwinContext();
ClaimsPrincipal user = ctx.Authentication.User;
IEnumerable<Claim> claims = user.Claims;
也许我失去了一些东西在这里。
Perhaps I am missing something here.
任何帮助将大大AP preciated和我道歉,如果这是一个新手的问题,这是我与OWIN和使用权利要求身份第一次经历。
Any help would be greatly appreciated and I apologise if this is a novice question, it's my first experience with OWIN and using Claims Identity.
感谢。
更新
,我加了他code,但我仍看不到获得索赔。请参考下面展示我所看到的,当鼠标悬停identity.Claims截图。
Based on Darin's answer, I added his code but still I fail to see access to the Claims. Please see screenshot below showing what I see when hovered over identity.Claims.
推荐答案
试试这个:
[Authorize]
public ActionResult SomeAction()
{
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
...
}
这篇关于MVC 5访问索赔身份的用户数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!