【发布时间】:2014-11-20 19:40:52
【问题描述】:
在我的代码 (ASP.NET Identity 2.1) 中,我将声明设置如下:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError("invalid_grant", "The user name or password is incorrect.");
return;
}
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,
OAuthDefaults.AuthenticationType);
ClaimsIdentity cookiesIdentity = await user.GenerateUserIdentityAsync(userManager,
CookieAuthenticationDefaults.AuthenticationType);
AuthenticationProperties properties = CreateProperties(
user.UserName,
oAuthIdentity,
user.FirstName,
user.LastName,
user.Organization);
AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
context.Validated(ticket);
context.Request.Context.Authentication.SignIn(cookiesIdentity);
}
这里是 CreateProperites 方法,然后添加角色声明:
public static AuthenticationProperties CreateProperties(
string userName,
ClaimsIdentity oAuthIdentity,
string firstName,
string lastName,
int organization)
{
IDictionary<string, string> data = new Dictionary<string, string>
{
{ "userName", userName},
{ "firstName", firstName},
{ "lastName", lastName},
{ "organization", organization.ToString()},
{ "roles",string.Join(":",oAuthIdentity.Claims.Where(c=> c.Type == ClaimTypes.Role).Select(c => c.Value).ToArray())}
};
return new AuthenticationProperties(data);
}
在我的客户端上,我发出一个令牌请求并像这样接收它:
this.$http({
method: 'POST',
url: '/Token',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: 'grant_type=password&username=' + encodeURIComponent(userName) + '&password=' + encodeURIComponent(password),
})
.success((data: any, status, headers, cfg) => {
self.data.roles = data.roles;
我可以看到 self.data.roles 正确填充了角色。现在回到服务器上,我想检查角色声明的内容。有人可以告诉我如何做到这一点吗?我知道我可以在方法中执行以下操作:
[HttpGet]
[Route("Retrieve")]
public async Task<IHttpActionResult> Retrieve()
{
var x = User;
x 获取
的值System.Security.Claims.ClaimsPrinciple and
System.Security.Claims.ClaimsIdentity
但在 x 内,我无法找到有关索赔本身的信息。
请注意,我确实尝试过之前在 SO 上发布的建议:
var identity = (ClaimsIdentity)User.Identity;
IEnumerable<Claim> claims = identity.Claims;
// The following line returns null
var roles = identity.Claims.Where(r => r.Type == "roles").FirstOrDefault();
但我仍然无法在声明中找到与 角色 声明相关的信息。我知道它必须在它到达客户时就在那里。
请注意,我正在寻找“角色”声明。不是任何系统生成的声明。但是我尝试添加自己的一个包含角色的串联列表。
【问题讨论】:
标签: asp.net asp.net-web-api asp.net-identity claims-based-identity