Monday, 22 February 2010

ASP.NET MVC Simple authentication without a database

Sometimes you just need a really simple authentication method in your ASP.NET MVC applications. The default MVC application has the necessary providers setup so that you can have a more flexible Membership system, but if you just want a single username and password, then this will help you.


In your web.config change the Authentication section to the following:
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880">
<credentials passwordFormat="Clear">
<user name="test" password="test"/>
</credentials>
</forms>
</authentication>

Then in the AccountModel.cs file, find the method ValidateUser and change the code to the following:

public bool ValidateUser(string userName, string password)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
if (String.IsNullOrEmpty(password)) throw new ArgumentException("Value cannot be null or empty.", "password");

return FormsAuthentication.Authenticate(userName, password);
}

The default setup should now work without using the provider.

0 comments:

Post a Comment