[英]How do I add a custom claim to authentication cookie generated by OpenIdConnect middleware in ASP.Net Core after authentication?
[英]How do I add a custom property to a Role Claim in .Net Core?
我正在使用 Cookie 身份验证而不是 Identity Core。 我正在循环浏览用户应该从自定义表中拥有的角色,并添加这样的角色声明:
if (aartsUser != null)
{
#region Create Claims
// UserName claim and StaffId claim. Will need StaffId to write to tables such as UploadStaffId for FacUpload.
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, loginModel.UserName),
new Claim("StaffId", aartsUser.StaffID.ToString())
};
// Role Claims
foreach(Position p in aartsUser.Positions)
{
claims.Add(new Claim(ClaimTypes.Role, p.Role.RoleCd));
}
#endregion
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(new ClaimsPrincipal(claimsIdentity));
return Redirect(loginModel?.ReturnUrl ?? "/");
}
此行中的 RoleCd:
claims.Add(new Claim(ClaimTypes.Role, p.Role.RoleCd));
来自我拥有的角色实体:
[Table("role")]
public class Role
{
[Key]
[Column("role_id")]
public short RoleID { get; set; }
[Column("role_nm")]
public string RoleName { get; set; }
[Column("role_cd")]
public string RoleCd { get; set; }
[Column("role_group_nm")]
public string RoleGroupName { get; set; }
[Column("role_class_cd")]
public string RoleClassCd { get; set; }
public List<Position> Positions { get; set; }
}
我的问题是如何向角色声明添加自定义属性。 我有一个帐户信息页面,用户可以在其中查看他们的角色。 但是我显示了自定义表中的 RoleCd。 我仍然想使用此代码作为角色,但我被要求还显示类似于文本描述的 RoleNm。
如何在此行中添加像 Description 这样的自定义属性?
claims.Add(new Claim(ClaimTypes.Role, p.Role.RoleCd));
类似的东西:
claims.Add(new Claim(ClaimTypes.Role, p.Role.RoleCd).Properties.Add("Description", p.Role.RoleName));
但它说不能从 void 转换为 System.Security.Claims.Claim。
我想通了。
这是我所做的:
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, loginModel.UserName),
new Claim("StaffId", aartsUser.StaffID.ToString())
};
// Role Claims
foreach(Position p in aartsUser.Positions)
{
claims.Add(new Claim(ClaimTypes.Role, p.Role.RoleCd));
Claim newClaim = claims.Where(c => c.Value == p.Role.RoleCd).FirstOrDefault();
newClaim.Properties.Add("Description", p.Role.RoleName);
}
根据您自己的答案,我有更好的解决方案。 因此,您无需再次查询声明。
foreach(Position p in aartsUser.Positions)
{
Claim newClaim = new Claim(ClaimTypes.Role, p.Role.RoleCd));
newClaim.Properties.Add("Description", p.Role.RoleName);
claims.Add(newClaim);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.