Reputation:
I am learning ASP.NET MVC and I have never worked with the .Net Authorisation, and Membership tool before.
I am creating an application that will let users log in and animals they own so it will have a number of tables
In tutorials I have looked at the membership and authorisation tool seems to create a new database for the login data. How would this work with my own custom tables?
Thanks
Upvotes: 1
Views: 689
Reputation: 6079
It's really easy to do, if you have custom tables. But in this case you have to check the password manually.
Here are few simple steps.
First, add forms authorization to your web.config file:
<authentication mode="Forms">
<forms loginUrl="~/login" defaultUrl="/" name=".ASPXFORMSAUTH" protection="All" slidingExpiration="true" path="/" timeout="50000000" />
</authentication>
Make sure you have controller properly configured in RouteConfig.cs
routes.MapRoute("Login", "login", new { controller = "Login", action = "Login" });
Make your own password validation function, based on information stored in your existing tables:
public bool ValidatePassword(string email, string password)
{
bool isValid = false;
// TODO: put your validation logic here
return isValid;
}
Note that you can use username or email. I prefer email, because users never forget their emails, but often have several usernames.
Create your Login controller:
public class LoginController : Controller
{
[HttpGet]
public ActionResult Login()
{
if(Request.IsAuthenticated)
{
return View("AlreadyLoggedIn");
}
return View();
}
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Login(LoginViewModel viewModel)
{
if(ModelState.IsValid)
{
var isPasswordValid = ValidatePassword(viewModel.Email, viewModel.Password);
if(isPasswordValid)
{
FormsAuthentication.SetAuthCookie(viewModel.Email, true);
// now the user is authenticated
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("password", "Invalid password");
}
}
return View(viewModel);
}
}
View model is pretty easy:
public class LoginViewModel
{
[Required(ErrorMessage = "Please type your email")]
[EmailAddress(ErrorMessage = "Please provide correct email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Please type your password")]
public string Password { get; set; }
}
And if you want to restrict access to some of your pages, use Authorize attribute:
public class AnotherController : Controller
{
[Authorize, HttpGet]
public ActionResult Index()
{
...
}
}
To summarize, you just need to put all your database login verification logic to ValidatePassword function, and that's it!
Upvotes: 3