c# - MVC:在使用 AAD 身份验证时添加和编辑身份声明角色名称
问题描述
我使用 AAD 来登录和验证用户,不幸的是没有我可以从 AAD 使用的基于角色的,所以我需要依赖数据库中设置的角色,但是,我不知道如何添加该用户的角色基于数据库中的内容,而不影响身份验证 cookie?
但是,我设法在我Startup.Auth
的内部手动添加了一个角色app.UseOpenIdConnectAuthentication
,就像这样
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = (context) =>
{
context.HandleResponse();
context.OwinContext.Response.Redirect("/Account/Login");
return Task.FromResult(0);
},
SecurityTokenValidated = async (x) =>
{
var identity = x.AuthenticationTicket.Identity;
//check the name, add additional claims
identity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", "Administrator"));
await Task.FromResult(0);
}
}
但是,当我Administrator
手动添加时,我不知道如何根据链接到数据库中用户的角色来更改它。我想一旦它击中我的控制器(这是我的家/索引),我也许可以更新角色,但很难找到有效的东西。
我想利用User.IsInRole("UserRoleNameHere")
.
任何帮助或想法将不胜感激!
解决方案
我能够找到解决方案!最终我所做的是向 ClaimsIdentity 添加一个新声明,注销以清除之前存储的身份,然后再次登录以使用新添加的声明添加新身份:
var result = (from U in db.Users
from R in U.Roles
join R2 in db.Roles on R.RoleId equals R2.Id
where U.Id == loggedInUserId
select new { R2.Name, U.UserName }).FirstOrDefault();
ClaimsIdentity identity = (ClaimsIdentity)User.Identity;
identity.AddClaim(new Claim("http://schemas.microsoft.com/ws/2008/06/identity/claims/role", result.Name));
IOwinContext context = new OwinContext();
context.Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
context.Authentication.SignIn(identity);
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
if (User.IsInRole("Administrator"))
{
isAdmin = true;
}
推荐阅读
- git - 为什么需要一次合并所有拉取请求
- authentication - oauth 隐式授权与授权码授权?
- python - 使用什么函数来更新 odoo 字段而不替换现有行
- double-click-advertising - DCM 忽略了我的 gclid 转换
- angular - 角度声明数据;任何如何在该变量中获取某些内容
- ios - 如何从地图套件中的两个 MKCircle 中找到交点坐标?
- image - Spring MVC - 将图像复制到 WEB-INF/assets 文件夹中
- mysql - 通过选择结果组添加排名列
- laravel - 无法对私有应用进行身份验证 - Laravel Notification、Laravel Echo、Socket
- ios - 添加到 UITableView 时在 Storyboard 中使用 UITableViewCells 的正确方法是什么