【问题标题】:MVC: Adding and Editing Identity Claim Role Name while using AAD authenticationMVC:在使用 AAD 身份验证时添加和编辑身份声明角色名称
【发布时间】:2019-10-27 19:15:52
【问题描述】:

我使用 AAD 来登录和验证用户,不幸的是没有我可以从 AAD 使用的基于角色的,所以我需要依赖数据库中设置的角色,但是,我不知道如何根据数据库中的内容为该用户添加角色,而不影响身份验证 cookie?

然而,我设法在app.UseOpenIdConnectAuthentication 内的Startup.Auth 中手动添加了一个角色,就像这样

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-mvc openid-connect claims-based-identity


    【解决方案1】:

    我找到了解决办法!最终我所做的是向 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;
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-04
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 2013-08-19
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      相关资源
      最近更新 更多