Authentification with Active Directory (AD) with Asp.Net MVC<!-- --> | <!-- -->Patrick Desjardins Blog
Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Authentification with Active Directory (AD) with Asp.Net MVC

Posted on: November 25, 2013

With Visual Studio 2013, you cannot simply choose "Intranet WebSite" to create a default website that use Active Directory. Nevertheless, a wizard allow you to create it. First, select create a new project and select a web application.

CreateNewWebApplication1 400x263

Second, you need to select MVC and to click change authentication.

CreateNewWebApplication2 400x282

This will result to a page where you will be able to select Organisation Authentification. Select On-Promise. This will let you specify the active directory URI.

CreateNewWebApplication3 400x280

And that's it.

You can also do it more manually. It's good to know because if you have to configure IIS, you will have to do some configuration. First, you need to disable anonymous authentication and allow windows authentication.

The web.config also need to tell that we use windows authentication.

1<system.web> <authentication mode="Windows" />
2 <roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
3 <providers>
4 <clear />
5 <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
6 </providers>
7 </roleManager>

This allow the use of the Authorize attribute over controllers and methods.

1[Authorize(Roles = "YOURDOMAIN\\\\Group1, YOURDOMAIN\\\\Group2")]
2public ActionResult YourMethod() {
3 //...

If you want to allow the user to log with the form instead of being automatically logged in, you need to specify a connection string in the web.config.

1<connectionStrings> <add name="ADConn" connectionString="LDAP://YourConnection" /> </connectionStrings>

Then, you need to setup the membership provider.

1<membership defaultProvider="ADMembership">
2 <providers>
3 <add name="ADMembership" type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, Version=, Culture=neutral, PublicToken=b03f5f7f11d50a3a" connectionStringName="ADConn" connectionUsername="domain/user" connectionPassword="pwd" />
4 </providers>