【发布时间】:2016-03-01 04:19:30
【问题描述】:
我在理解声明时遇到问题,尤其是角色。
以下给了我分配给用户的两个角色
var roles = UserManager.GetRolesAsync(user.Id).Result;
但是当我得到声明并遍历它时,我只得到第一个角色。两个角色我都没有。请注意,我在登录时没有在声明中设置任何角色。
操作代码
IEnumerable<Claim> claims = null;
var identity = HttpContext.User.Identity as ClaimsIdentity;
if (identity != null && identity.Claims != null && identity.Claims.Any())
{
claims = identity.Claims;
}
return View(claims);
以及对应的视图代码
@model IEnumerable<System.Security.Claims.Claim>
@{
ViewBag.Title = "Display Claims";
}
<h2>Display Claims</h2>
@if (Model == null)
{
<p class="alert-danger">No claims found</p>
}
else
{
<table class="table table-bordered">
<tr>
<th>Subject</th>
<th>Issuer</th>
<th>Type</th>
<th>Value</th>
</tr>
@foreach (var claim in Model.OrderBy(x => x.Type))
{
<tr>
<td>@claim.Subject.Name</td>
<td>@claim.Issuer</td>
<td>@Html.ClaimType(claim.Type)</td>
<td>@claim.Value</td>
</tr>
}
</table>
}
这是输出。我在这里错过了什么?
而表有两种作用
更新 #1
我添加了名字和姓氏作为远程声明,登录并且两个角色现在都显示了。我没有改变任何东西。所以现在我更困惑了......
这里是添加远程声明的提供者
public static class ClaimsUserInfoProvider
{
public static IEnumerable<Claim> GetClaims(ClaimsIdentity user, ApplicationUser applicationUser)
{
var claims = new List<Claim>();
claims.Add(CreateClaim(ClaimTypes.GivenName, applicationUser.FirstName + " " + applicationUser.LastName));
return claims;
}
private static Claim CreateClaim(string type, string value)
{
return new Claim(type, value, ClaimValueTypes.String, "RemoteClaims");
}
}
以及使用声明提供程序的登录操作
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindAsync(model.UserName, model.Password);
if (user == null)
{
ModelState.AddModelError("", "Invalid user name or password.");
}
else
{
var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
//add claims
identity.AddClaims(ClaimsUserInfoProvider.GetClaims(identity, user));
AuthenticationManager.SignOut();
AuthenticationManager.SignIn(new AuthenticationProperties
{
IsPersistent = model.RememberMe
}, identity);
if (!String.IsNullOrEmpty(model.ReturnUrl))
{
return Redirect(model.ReturnUrl);
}
return RedirectToAction("Index", "Home");
}
}
return View(model);
}
【问题讨论】:
-
这个答案可能对stackoverflow.com/questions/21688928/…有帮助
-
我以前看过这个,但看不懂。在过去的一个小时左右,我一直在阅读它,现在这更有意义了。我已将更新#1 放在我的问题帖子中。两个角色现在都显示了,不知道为什么之前没有显示。
-
我会问一个愚蠢的问题 - 您是否清除了浏览器中的 cookie?您是否退出并再次登录?
-
事实上我做了,我已经放置了 update#1.. 两个角色现在都显示了。
-
我在某处读到会员提供者默认不支持声明,就像用户和角色一样。我的 2 美分
标签: c# asp.net asp.net-identity claims-based-identity