我正在使用 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 以执行登录 .
The problem I am having is that I'm not sure how to access the claims in the rest of my application, either in Controllers or in Razor Views.
我曾尝试过本教程中列出的方法
例如,我在我的Controller代码中尝试了这一点,试图访问传递给Claims的值,但是,user.Claims等于null
var ctx = HttpContext.GetOwinContext();
ClaimsPrincipal user = ctx.Authentication.User;
IEnumerable<Claim> claims = user.Claims;
也许我在这里遗漏了一些东西 .
UPDATE
根据Darin的回答,我添加了他的代码,但我仍然看不到索赔的访问权限 . 请看下面的截图,显示我在身份上盘旋时看到的内容 . 声明 .
11 回答
试试这个:
你也可以这样做:
Update
根据评论提供进一步说明 .
如果要在系统中创建用户,如下所示:
您应该自动填写与您的身份相关的一些声明 .
要在用户进行身份验证后添加自定义声明,您可以执行以下操作:
当Darin已经回答上述问题或正如我所说的那样,索赔可以回读 .
当您在下面通过以下身份致电时,声明会保留:
我创建自己的扩展类来查看我需要的东西,所以当我需要进入我的控制器或我的视图时,我只将这个使用添加到我的命名空间:
在我的控制器中:
在我的剃须刀:
如果您不想一直使用声明,则可以选择此选项 . 看看Ben Foster的这个tutorial .
然后你可以添加一个基本控制器 .
在你的控制器中,你会做:
你也可以这样做 .
要进一步了解Darin的答案,您可以使用 FindFirst 方法获取您的具体声明:
但是,最好在“GenerateUserIdentityAsync”方法中添加声明,尤其是在启用Startup.Auth.cs中的regenerateIdentity时 .
@Rosdi Kasim答案的最短和简化版本是
Claimname
是您想要检索的索赔,即如果您正在寻找"StreedAddress"索赔,那么以上答案将是这样的请记住,为了查询IEnumerable,您需要引用system.linq .
它将为您提供所需的扩展对象:
根据ControllerBase类,您可以获取执行操作的用户的声明 .
这是你如何在一行中做到这一点 .