I wanted to add a simple login. So I thought the best way would be to add the credentials in a database and then query that and if the username and password mathches you get logged in. This is working, well it querys the db and you get logged in and redirected to home. Then I tried accessing home through the url and noticed that I can do that without login. So then I figured that I should use the
[Authorize]
attribute on the Home Controller as I don't want unauthorized users to access it so the should be redirected back to the login page. This does not work. when I use authorize on the controller I get a error in the application.
Object reference not set to an instance of an object.
In the web.config it looks like this:
<authentication mode="Forms">
<forms loginUrl="~/Login/Index" timeout="2880" /> <-- I have changed the login url to my login controller.
</authentication>
And my login controller like this.
public ActionResult Index(UserModel model) <-- I query the db in the model.
{
if (!ModelState.IsValid)
{
return View(model);
}
if(!model.IsAdmin(model.UserName, model.Password))
{
ModelState.AddModelError("username", "you are not a admin");
return View(model);
}
FormsAuthentication.SetAuthCookie(model.UserName, false);
return RedirectToAction("Index", "Home");
}
So how is the proper way to use this Authorize attribute? Can I even use it the way I'm using it? Am I missing something in the web.config? Regards!
Some update to this. As it was not working I added this to the web.config:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="5">
</forms>
</authentication>
<membership defaultProvider="MyMembershipProvider">
<providers>
<clear/>
<add name="MyMembershipProvider" type="MyNamespace.MyMembershipProvider"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
userIsOnlineTimeWindow="2"
requiresUniqueEmail="false"
passwordFormat="Hashed"
maxInvalidPasswordAttempts="5"
minRequiredPasswordLength="6"
minRequiredNonalphanumericCharacters="0"
passwordAttemptWindow="10"
applicationName="/" />
</providers>
</membership>
And a membershipprovider with hardcoded credentials:
public class MyMembershipProvider : MembershipProvider
{
public override bool ValidateUser(string username, string password)
{
if (username.Equals("user", StringComparison.CurrentCultureIgnoreCase) && password.Equals("myPassword"))
return true;
else
return false;
}
Then I tried decorating my HomeController with the Authorization attribute like this:
[Authorize()]
public class HomeController : Controller
{}
But still getting the same error. I mean I can login but when I reach "Home" I get the same error as before. What in earths name is this?! Any clues to this?!
Regards!