授权角色无效

时间:2015-09-01 10:32:10

标签: c# asp.net-mvc authorization

这是控制器中的注册和登录操作方法:

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方法,如果用户没有登录,但是用户已经登录并且仍在进行中,那么应该发生什么

1 个答案:

答案 0 :(得分:0)

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

 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"});
        } 
    }