Saturday, August 10, 2019

Part 1- How to implement custom Forms Authentication in ASP.NET MVC4 application

Step - 1 : Create New Project. Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Basic Application > Select view engine Razor > OK

Step-2: Add a new Controller.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name (Home) > Select Templete "empty MVC Controller"> Add.

Step-3: Add new action into your controller for anonymous user

Here I have used "Index" Action. Please write this following code
  1. [AllowAnonymous] //This is for Un-Authorize User
  2. public ActionResult Index()
  3. {
  4. return View();
  5. }

Step-4: Add view for the Action & design.

Right Click on Action Method (here right click on index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add. 
Complete View
 
  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4.  
  5. <h2>Index</h2>
  6.  
  7. <h3>Welcome Guest - This is for all the anonymous user</h3>

Step-5: Add an another action into your controller for Authorized User (Later we will see Role Based user)

Here I have used "Index" Action. Please write this following code
  1. [Authorize] // This is for Authorize user
  2. public ActionResult MyProfile()
  3. {
  4. return View();
  5. }

Step-6: Add view for the Action & design.

Right Click on Action Method (here right click on index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
  Complete View 
  1. @{
  2. ViewBag.Title = "MyProfile";
  3. }
  4.  
  5. <h2>MyProfile</h2>
  6.  
  7. <h3>Welcome @(Request.IsAuthenticated ? HttpContext.Current.User.Identity.Name : "Guest") - This is for Authorized user </h3>
Optional: Here I have added Bootstrap css in the layout page for Responsive design.

Step-7: Create a Class (ViewModel).

Go to Solution Explorer > Right Click on the Models Folder > Add > Class > Enter class name > Add.

  1. using System.ComponentModel.DataAnnotations;
  2.  
  3. namespace MvcAuthentication.Models
  4. {
  5. public class Login
  6. {
  7. [Required(ErrorMessage="Username required.",AllowEmptyStrings=false)]
  8. public string Username { get; set; }
  9.  
  10. [Required(ErrorMessage = "Password required.", AllowEmptyStrings = false)]
  11. [DataType( System.ComponentModel.DataAnnotations.DataType.Password)]
  12. public string Password { get; set; }
  13. public bool RememberMe { get; set; }
  14. }
  15. }

Step-8: Add an another Controller (here "MyAccountController") for Manage Account Related Action like Login, logout etc.

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name (MyAccount) > Select Templete "empty MVC Controller"> Add.

Step-9: Add a new action into the controller (here "MyAccountController") for Logged In

Here I have used "Login" Action. Please write this following code
  1. public ActionResult Login()
  2. {
  3. return View();
  4. }

Step-10: Add view for the "Login" Action & design.

Right Click on Action Method (here right click on index action) > Add View... > Enter View Name > Select View Engine (Razor) > Add.
  Complete View 
  1. @model MvcAuthentication.Models.Login
  2.  
  3. @{
  4. ViewBag.Title = "Login";
  5. }
  6.  
  7. <h2>Login</h2>
  8.  
  9. @using (Html.BeginForm()) {
  10. @Html.ValidationSummary(true)
  11. @Html.AntiForgeryToken()
  12. <fieldset>
  13. <legend>Login</legend>
  14.  
  15. <div class="editor-label">
  16. @Html.LabelFor(model => model.Username)
  17. </div>
  18. <div class="editor-field">
  19. @Html.EditorFor(model => model.Username)
  20. @Html.ValidationMessageFor(model => model.Username)
  21. </div>
  22.  
  23. <div class="editor-label">
  24. @Html.LabelFor(model => model.Password)
  25. </div>
  26. <div class="editor-field">
  27. @Html.EditorFor(model => model.Password)
  28. @Html.ValidationMessageFor(model => model.Password)
  29. </div>
  30.  
  31. <div class="editor-label">
  32. @Html.LabelFor(model => model.RememberMe)
  33. </div>
  34. <div class="editor-field">
  35. @Html.EditorFor(model => model.RememberMe)
  36. @Html.ValidationMessageFor(model => model.RememberMe)
  37. </div>
  38.  
  39. <p>
  40. <input type="submit" value="Create" />
  41. </p>
  42. </fieldset>
  43. }
  44.  
  45. <div>
  46. @Html.ActionLink("Back to List", "Index")
  47. </div>
  48.  
  49. @section Scripts {
  50. @Scripts.Render("~/bundles/jqueryval")
  51. }
  52.  

Step-11: Edit web.config for Enable Forms authentication.

  1. <authentication mode="Forms">
  2. <forms loginUrl="~/MyAccount/Login" timeout="2880" />
  3. </authentication>

RUN APP HERE FOR TEST IS ALL WORKING AS EXPECTED OR NOT

Step-12: Add a Database for do login from database

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-13: Create a table.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.

In this example, I have used table as below 

Step-14: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >

Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish. 

Step-15: Add another action in our controller (here "MyAccountController") for POST method for login from database.

  1. [HttpPost]
  2. [ValidateAntiForgeryToken]
  3. public ActionResult Login(Login l, string ReturnUrl = "")
  4. {
  5. using (MyDatabaseEntities dc = new MyDatabaseEntities())
  6. {
  7. var user = dc.Users.Where(a => a.Username.Equals(l.Username) && a.Password.Equals(l.Password)).FirstOrDefault();
  8. if (user != null)
  9. {
  10. FormsAuthentication.SetAuthCookie(user.Username, l.RememberMe);
  11. if (Url.IsLocalUrl(ReturnUrl))
  12. {
  13. return Redirect(ReturnUrl);
  14. }
  15. else
  16. {
  17. return RedirectToAction("MyProfile", "Home");
  18. }
  19. }
  20. }
  21. ModelState.Remove("Password");
  22. return View();
  23. }

Step-16: Add an another action into our controller (here "MyAccountController") for Logout

Here I have used "Logout" Action. Please write this following code
  1. [Authorize]
  2. public ActionResult Logout()
  3. {
  4. FormsAuthentication.SignOut();
  5. return RedirectToAction("Index", "Home");
  6. }

Step-17: Update Layout View for Show Login / Logout link.

  1. <li>
  2. @{
  3. if (Request.IsAuthenticated)
  4. {
  5. using (Html.BeginForm("Logout","MyAccount", FormMethod.Post,new{ id = "logoutForm"}))
  6. {
  7. <a href="javascript:document.getElementById('logoutForm').submit()">Logout</a>
  8. }
  9. }
  10. else
  11. {
  12. @Html.ActionLink("Login","Login","MyAccount")
  13. }
  14. }
  15. </li>

Step-18: Run Application.

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...