首页 > 解决方案 > 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").

任何帮助或想法将不胜感激!

标签: c#asp.net-mvcopenid-connectclaims-based-identity

解决方案


我能够找到解决方案!最终我所做的是向 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;
            }

推荐阅读