In ASP.NET MVC, default membership works with pre-defined/specified information source wherever programmer don’t worry regarding something associated with authentication. To implement authentication with desired information source, programmer should implement custom membership as explained within the article. using custom membership, programmer will simply authenticate user’s visit through self-written code.
This article can describe some easy steps to finish the task:
1. Create a class named “Custom_Membership” in Models folder in your MVC application.
2. Inherit this from MembershipProvider class exists in “System.Web.Security” namespace.
3. Right click on MembershipProvider and choose on “Implement Abstract Class”, it’ll all the override function ought to be implement by us.
simply implement ValidateUser() method and replace that operate with the subsequent code:
1 2 3 4 5 6 7 8 |
public override bool ValidateUser(string username, string password) { if (username == "admin" && password == "password") { return true; } return false; } |
Go to AccountController –> Login action and alter the login practicality as:
1 2 3 4 5 6 7 8 9 10 |
public ActionResult Login(LoginModel model, string returnUrl) { if (ModelState.IsValid && Membership.ValidateUser(model.UserName, model.Password)) { FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe); return RedirectToLocal(returnUrl); } ModelState.AddModelError("", "The user name or password provided is incorrect."); return View(model); } |
Open web.config file of the root and add following code in system.web tag
1 2 3 4 5 6 7 |
<membership defaultProvider="Custom_Membership"> <providers> <clear/> <add name="Custom_Membership" type="CustomMembershipP.Models.Custom_Membership"/> </providers> </membership> |
Run the MVC application and open Login page, it provide miscalculation related to membership, to resolve through error simply delete “[InitializeSimpleMembership]” attribute from AccountController.
Finally, RUN the application and enter username and password as provided on top of in ValidateUser() function. it’ll login with success, currently you’ll be able to override any of the function in your custom membership class.