I am really having hard time working with Authorize; After checking the username and password of a registred user, the user should be redirected to the account page. In the account Controller I am using Authorize attribute as following:
[Authorize]
public ActionResult Index(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
The thing is if I compile the code and try to login with the right username and password, I will get an HTML 401 unauthorized error which is wierd!.
I tried to read a bit about it, in a book of Jon Galloway called Professional ASP.NET MVC 5, he explained that Web.config should be also edited when using [Authorize] (i dont know if i got it right!). So i tried to edit Web.config as following:
<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="2880" />
</authentication>
Now, i dont get the error anymore but when I change the url, Iam able to see the account page without to login which is bad and means that [Authorize] attribute is not working.
I Know that Authorize works with Roles and Users, i could write for example [Authorize(Uers = "blabla")], But the thing in my application that all users that are registred in the EF DB are able to see the account page. Anyone can help me to solve this problem please:)?
Here you have the code of my login Form
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModels lgm)
{
if (ModelState.IsValid)
{
// Check if username exist
var dbUser = db.RegisterTables.FirstOrDefault(x => x.tUserName.ToLower().Equals(lgm.username));
if (dbUser != null)
{
if (Security.IsCorrectPassword(lgm.password, dbUser))
{
FormsAuthentication.SetAuthCookie(lgm.username, true);
return RedirectToAction("Index", "Account");
}
else ModelState.AddModelError("", "Check user or pass.");
}
else ModelState.AddModelError("", "Check user or pass.");
}
return View(lgm);
}
The code of the /Account/Index is just a normal ActionResult thats returns the view of the account.