MVC 4表单身份验证无法与[授权]一起使用

Car*_*ras 7 c# asp.net-mvc forms-authentication authorize asp.net-mvc-4

我正在学习MVC4,我正在关注Pro ASP NET MVC4第4版的书,以创建一个体育商店项目.

我一直在webforms中开发,我试图弄清楚表单身份验证在MVC4中是如何工作的.

这是我取得的成就:

Web.Config中

<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880"/>  </authentication>
Run Code Online (Sandbox Code Playgroud)

AccountController登录动作:

[HttpPost]
        public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (authProvider.Authenticate(model.UserName, model.Password))
                {
                    return Redirect(returnUrl ?? Url.Action("Index", "Admin"));
                }
                else
                {
                    ModelState.AddModelError("", "Incorrect username or password");
                    return View();
                }
            }
            else
            {
                return View();
            }
        }
Run Code Online (Sandbox Code Playgroud)

认证提供者:

public bool Authenticate(string username, string password) {
            bool result = FormsAuthentication.Authenticate(username, password);
            if (result)
            {
                FormsAuthentication.SetAuthCookie(username, false);
            }

            return result;

        }
Run Code Online (Sandbox Code Playgroud)

我正在设置AuthCookie,现在我想知道,如何保护AccountController之外的其他控制器和操作

该应用程序有一个名为AdminController的控制器,您可以在其中编辑
以下{controller/action}下的产品和产品列表

管理员/指标

所以,如果我不理解理论,如果用户没有登录AccountController,他们就不应该在声明中使用[Authorize]标签调用操作:

 public class AdminController : Controller
    {
        private IProductRepository repository;


        public AdminController(IProductRepository repo)
        {
            repository = repo;
        }

       [Authorize]
        public ActionResult Index()
        {

            return View(repository.Products);
        }
   }
Run Code Online (Sandbox Code Playgroud)

问题是我可以毫无问题地调用管理控制器的索引操作,而无需引入登录.

我需要一些指导来了解它是如何工作的.我做了一些研究,找不到任何东西,这本书没有涵盖这个主题.

提前致谢.

编辑:我关闭了Chrome浏览器并且无需更改任何内容.我正在使用选项卡,我猜即使停止并开始调试,cookie也处于活动状态.

Dar*_*rov 9

如果使用[Authorize]属性修饰控制器操作(就像您的Admin/Index操作一样),如果请求中没有有效的表单身份验证cookie,则无法调用此操作.

同样在您的Login操作中,成功进行身份验证后,您不应返回视图,但应重定向,以便正确设置cookie并在后续请求中使用.

以下是未经过身份验证的用户尝试访问受保护Admin/Index操作时应发生的情况.该[Authorize]属性将抛出401异常,如您所知,经典WebForms将被Forms Authentication模块截获,您将被重定向到loginUrlweb.config中配置的配置,并将ReturnUrl查询字符串参数传递给最初请求的受保护资源.

因此,您必须Login在未使用该[HttpPost]属性修饰的帐户控制器上执行操作,并且该操作应该为包含登录视图的视图提供服务.请求将如下所示:

/Account/Login?ReturnUrl=%2Fadmin%2Findex
Run Code Online (Sandbox Code Playgroud)

  • 废话,我关闭了我的浏览器并清理了缓存,现在它正在工作而不会改变任何东西 (4认同)