Membership in ASP.NET MVC

1. Edit ~\web.config to include the following membership configuration.

<configuration>
	<connectionStrings>
		<clear />
		<add name="ADConnectionString" connectionString="LDAP://ldap.unfuddle.com/CN=Users,DC=unfuddle,DC=com" />
	</connectionStrings>
	<system.web>
		<authentication mode="Forms">
			<forms loginUrl="~/Account/LogOn" timeout="30" />
		</authentication>
		<membership defaultProvider="ADMembershipProvider">
			<providers>
				<clear />
				<add name="ADMembershipProvider" 
					type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" 
					connectionStringName="ADConnectionString" connectionUsername="<domainName>\administrator" connectionPassword="password"
					applicationName="Unfuddle.MvcWebApp" />
			</providers>
		</membership>
	</system.web>
</configuration>

2. Setup Forms Authentication

3. In AccountController.LogOn action method, use Membership to perform the authentication.

public class AccountController : Controller
{
	//
	// 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);
	}
}

References

Advertisements

One thought on “Membership in ASP.NET MVC

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