无法为用户设置角色

时间:2019-12-16 18:29:16

标签: c# asp.net-mvc authentication .net-core

我目前正在使用.NET Core,并且正在尝试为用户分配/认证角色。例如,名为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");

0 个答案:

没有答案