授权角色不工作

本文关键字:工作 角色 授权 | 更新日期: 2023-09-27 18:10:44

这是我在控制器中的Sign Up和Login操作方法:

public ActionResult SignUp()
    {
        return View();
    }
    [HttpPost]
    public ActionResult SignUp(User _user)
    {
        _user.Authorize = CustomRoles.RegisteredUser;
        int lastuserid = entities.Users.Last().UserID;
        _user.UserID = lastuserid + 1;
        if (ModelState.IsValid)
        {
            Roles.AddUserToRole(_user.UserName, CustomRoles.RegisteredUser);
            entities.Users.Add(_user);
            entities.SaveChanges();
            RedirectToAction("Index");
        }
        return View(_user);
    }
    public ActionResult Login()
    {
        LoginViewModel LVM = new LoginViewModel();
        HttpCookie existingCookie = Request.Cookies["UserName"];
        if (existingCookie != null)
        {
            LVM.UserName = existingCookie.Value;
        }
        return View(LVM);
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Login(LoginViewModel u)
    {
        if (ModelState.IsValid)
        {
            if (u.RememberMe==true)
            {
                HttpCookie existingCookie = Request.Cookies["UserName"];
                if (existingCookie != null)
                {
                    existingCookie.Value = u.UserName;
                    existingCookie.Expires = DateTime.Now.AddHours(-20);
                }

                HttpCookie newCookie = new HttpCookie("UserName", u.UserName);
                newCookie.Expires = DateTime.Today.AddMonths(12);
                Response.Cookies.Add(newCookie);
            }
            var v = entities.Users.Where(a => a.UserName.Equals(u.UserName) && a.Password.Equals(u.Password)).FirstOrDefault();
            if (v != null)
            {
                System.Web.HttpContext.Current.Session["UserName"] = u.UserName;
                return RedirectToAction("Index");
            }
        }
        return View(u);
    }

这里是它们应该去的动作方法的示例,其中一些在不同的控制器中但它们的结果是相同的:

 [Authorize(Roles = CustomRoles.RegisteredUser)]
    public ActionResult Orders(User U)
    {
        return View();
    }
[Authorize(Roles = CustomRoles.Manager)]
    public ActionResult Stock()
    {
        return View(entities.Cars.ToList());
    }

发生的是我被重定向回Login方法,这是应该发生的如果用户没有登录,但用户登录了,它仍然发生

授权角色不工作

您正在尝试实现表单授权,但我认为您忘记了使用HttpContext.User.IsInRole方法来检测用户是否可以访问操作的授权属性。要解决这个问题,您可以通过web配置表单授权。或者你手动分配你的HttpContext。用户通过HttpModule或在Global.asax.cs中使用应用程序事件,例如:

 protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
    {
        HttpContext context = ((HttpApplication)sender).Context;
        HttpCookie existingCookie = Request.Cookies["UserName"];            
        if (existingCookie != null) {
             context = new  new GenericPrincipal(new GenericIdentity(existingCookie.Value), new string[]{"Admin", "Manager"});
        } 
    }