Forms Authentication in ASP.NET MVC

1. Edit ~\web.config to include the following forms-based authentication configuration.

<system.web>
	<authentication mode="Forms">
		<forms loginUrl="~/Account/LogOn" timeout="30" />
	</authentication>
</system.web>

2. Register AuthorizeAttribute in ~\App_Start\FilterConfig.cs.

filters.Add(new AuthorizeAttribute());

3. Add view model LogOnViewModel in ~\Models\Account\LogOnViewModel.cs.

public class LogOnViewModel
{
	[Required]
	[Display(Name = "User name")]
	public string UserName { get; set; }

	[Required]
	[DataType(DataType.Password)]
	[Display(Name = "Password")]
	public string Password { get; set; }

	[Display(Name = "Remember me?")]
	public bool RememberMe { get; set; }
}

4. Add controller AccountController and LogOn action methods for both HttpGet & HttpPost.

public class AccountController : Controller
{
	//
	// GET: /Account/LogOn
	[AllowAnonymous]
	public ActionResult LogOn()
	{
		LogOnViewModel model = new LogOnViewModel();

		return View(model);
	}

	//
	// POST: /Account/LogOn
	[AllowAnonymous]
	[HttpPost]
	public ActionResult LogOn(LogOnViewModel model, string returnUrl)
	{
		if (this.ModelState.IsValid && Membership.ValidateUser(model.UserName, model.Password))
		{
			FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
			if (this.Url.IsLocalUrl(returnUrl))
			{
				return Redirect(returnUrl);
			}
			else
			{
				return RedirectToAction("Index", "Home");
			}
		}

		// If we got this far, something failed, redisplay form
		this.ModelState.AddModelError("", "Incorrect user name or password.");
		return View(model);
	}

	//
	// POST: /Account/LogOff
	[HttpPost]
	public ActionResult LogOff()
	{
		FormsAuthentication.SignOut();

		return RedirectToAction("Index", "Home");
	}
}

5. Add view in ~\Views\Account\LogOn.cshtml.

@model SecurityApp.Models.Account.LogOnViewModel
@{
    Layout = null;
    ViewBag.Title = "Log On";

    ViewBag.ReturnUrl = Request["ReturnUrl"];
}
<!DOCTYPE html>
<html>
......
<body>
    <h2>@ViewBag.Title</h2>
    @using (Html.BeginForm(null, null, new { returnUrl = ViewBag.ReturnUrl }, FormMethod.Post))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)<br />
        @Html.TextBoxFor(m => m.UserName, new { placeholder = Html.DisplayNameFor(m => m.UserName) })<br />
        @Html.PasswordFor(m => m.Password, new { placeholder = Html.DisplayNameFor(m => m.Password) })<br />
        @Html.CheckBoxFor(m => m.RememberMe)
        @Html.DisplayNameFor(m => m.RememberMe)<br />
        <button type="submit">Log On</button>
    }

    ......
</body>
</html>

6. In ~\Views\Shared\_Layout.cshtml, add a HTML form to handle log off.

@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logOffForm" }))
{
	@Html.AntiForgeryToken()
}

7. In ~\Views\Shared\_Layout.cshtml, add a hyperlink to log off.

<a href="javascript:$('#logOffForm').submit()">Log Off</a>

References

Advertisements

4 thoughts on “Forms Authentication in ASP.NET MVC

  1. Hello,
    Using above code has one issue. Lets say I login to my website and keep page idle for few hours.My session already expired. Now, I click on Logout link to log out from website. It redirects me to the login page with ReturnUrl as logout URL.. now once I login using my credentials.. Again it redirects me to the Login url after successful login as returnUrl is set as logout URL and I have to login again to go to home page.

    Please provide me solution for the same.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s