首页 > 解决方案 > 无法为用户设置角色

问题描述

我目前正在使用 .NET Core,并且正在尝试为用户分配/验证角色。例如,一个名为 admin 的管理员Robert 登录到系统,一个名为的角色admin将分配给他。我尝试过ClaimsPrincipal这样做,但它对我不起作用。我可以给点建议吗?

以下是我尝试过的代码:

public ActionResult Login (User user)
        {
            if (!AuthenticateUser(user.username, user.password, out ClaimsPrincipal principal))
            {
                //Error Message
            }
            else
            {
                HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    principal,
                    new AuthenticationProperties
                    {
                        IsPersistent = user.rememberMe
                    });
            }

            return RedirectToAction("Index", "Home");
        }

private bool AuthenticateUser(string username, string password, out ClaimsPrincipal principal)
        {
            principal = null;

            DataTable ds = DatabaseUtil.GetTable(SQL, username, password);
            if (ds.Rows.Count == 1)
            {
                principal =
                   new ClaimsPrincipal( 
                      new ClaimsIdentity(
                         new Claim[] {
                        new Claim(ClaimTypes.NameIdentifier, username),
                        new Claim(ClaimTypes.Name, ds.Rows[0][username].ToString()),
                        new Claim(ClaimTypes.Role, ds.Rows[0][role].ToString())
                         }, "Basic"
                      )
                   );

                return true;

            }
            return false;
        }

我什至尝试使用这组代码来检查当前用户是否被分配/真实。但是,当我进行调试时,它显示Authenticate: False.

System.Security.Claims.ClaimsPrincipal currentUser = this.User;
bool IsAdmin = currentUser.IsInRole("admin");

标签: c#asp.net-mvcauthentication.net-core

解决方案


推荐阅读