I am learning MVC4 right now and I am following the 4th Pro ASP NET MVC4 book to create the Sports Store project.
I always developed in webforms, and I'm trying to figure out how forms authentication works in MVC4.
Here is what I have achieved:
Web.config
<authentication mode="Forms"> <forms loginUrl="~/Account/Login" timeout="2880"/> </authentication>
Logging into AccountController Action:
[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(); } }
Authorization Provider:
public bool Authenticate(string username, string password) { bool result = FormsAuthentication.Authenticate(username, password); if (result) { FormsAuthentication.SetAuthCookie(username, false); } return result; }
I install AuthCookie, and now I would like to know how to protect other controllers and actions from AccountController
The application has a controller called AdminController, where you can edit products and the list of products in the {controller / action} section
Admin / Index
So, if I donβt miss the theory, if the user does not register in the AccountController, they cannot trigger actions with the [Authorize] tag on the declaration:
public class AdminController : Controller { private IProductRepository repository; public AdminController(IProductRepository repo) { repository = repo; } [Authorize] public ActionResult Index() { return View(repository.Products); } }
The fact is that I can trigger the Index Admin Controller action without any problems and without entering a login.
I need some guidance to understand how this works. I did some research and found nothing, and the book does not cover this topic.
Thanks in advance.
EDIT: I closed the Chrome browser and worked without changing anything. I worked with tabs and I think the cookie was active, even stopping and starting debugging.