Você está na página 1de 11

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.

2. [AllowAnonymous] //This is for Un-Authorize User

3. public ActionResult Index()

4. {

5. return View();

6. }

7.

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. @{

3. ViewBag.Title = "Index";

4. }

5.

6. <h2>Index</h2>

7.

8. <h3>Welcome Guest - This is for all the anonymous user</h3>

9.

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.

2. [Authorize] // This is for Authorize user

3. public ActionResult MyProfile()

4. {

5. return View();

6. }

7.

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. @{

3. ViewBag.Title = "MyProfile";

4. }

5.

6. <h2>MyProfile</h2>

7.

8. <h3>Welcome @(Request.IsAuthenticated ?
HttpContext.Current.User.Identity.Name : "Guest") - This is for
Authorized user </h3>

9.

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.

2. using System.ComponentModel.DataAnnotations;

3.

4. namespace MvcAuthentication.Models

5. {

6. public class Login

7. {
8. [Required(ErrorMessage="Username
required.",AllowEmptyStrings=false)]

9. public string Username { get; set; }

10.

11. [Required(ErrorMessage = "Password required.",


AllowEmptyStrings = false)]

12.
[DataType( System.ComponentModel.DataAnnotations.DataType.Passwor
d)]

13. public string Password { get; set; }

14. public bool RememberMe { get; set; }

15. }

16. }

17.

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.

2. public ActionResult Login()

3. {
4. return View();

5. }

6.

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.

2. @model MvcAuthentication.Models.Login

3.

4. @{

5. ViewBag.Title = "Login";

6. }

7.

8. <h2>Login</h2>

9.

10. @using (Html.BeginForm()) {

11. @Html.ValidationSummary(true)

12. @Html.AntiForgeryToken()

13. <fieldset>

14. <legend>Login</legend>

15.

16. <div class="editor-label">


17. @Html.LabelFor(model => model.Username)

18. </div>

19. <div class="editor-field">

20. @Html.EditorFor(model => model.Username)

21. @Html.ValidationMessageFor(model => model.Username)

22. </div>

23.

24. <div class="editor-label">

25. @Html.LabelFor(model => model.Password)

26. </div>

27. <div class="editor-field">

28. @Html.EditorFor(model => model.Password)

29. @Html.ValidationMessageFor(model => model.Password)

30. </div>

31.

32. <div class="editor-label">

33. @Html.LabelFor(model => model.RememberMe)

34. </div>

35. <div class="editor-field">

36. @Html.EditorFor(model => model.RememberMe)

37. @Html.ValidationMessageFor(model =>


model.RememberMe)

38. </div>
39.

40. <p>

41. <input type="submit" value="Create" />

42. </p>

43. </fieldset>

44. }

45.

46. <div>

47. @Html.ActionLink("Back to List", "Index")

48. </div>

49.

50. @section Scripts {

51. @Scripts.Render("~/bundles/jqueryval")

52. }

53.

54.

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

1.

2. <authentication mode="Forms">

3. <forms loginUrl="~/MyAccount/Login" timeout="2880" />

4. </authentication>

5.
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.

2. [HttpPost]
3. [ValidateAntiForgeryToken]

4. public ActionResult Login(Login l, string ReturnUrl = "")

5. {

6. using (MyDatabaseEntities dc = new MyDatabaseEntities())

7. {

8. var user = dc.Users.Where(a =>


a.Username.Equals(l.Username) &&
a.Password.Equals(l.Password)).FirstOrDefault();

9. if (user != null)

10. {

11. FormsAuthentication.SetAuthCookie(user.Username,
l.RememberMe);

12. if (Url.IsLocalUrl(ReturnUrl))

13. {

14. return Redirect(ReturnUrl);

15. }

16. else

17. {

18. return RedirectToAction("MyProfile", "Home");

19. }

20. }

21. }

22. ModelState.Remove("Password");

23. return View();


24. }

25.

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.

2. [Authorize]

3. public ActionResult Logout()

4. {

5. FormsAuthentication.SignOut();

6. return RedirectToAction("Index", "Home");

7. }

8.

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.


DOWNLOAD LIVE DEMO

Você também pode gostar