![](/img/trans.png)
[英]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.