in

Blog By Bob

Blog by Bob

Active Directory Membership and Roles in ASP.NET 2.0

Most of the things I read about using AD with ASP.NET ends up being way more complex than it needs to be. Toss this in your web.config between the system.web tags:

<authentication mode="Windows" />
<
identity impersonate="true"/>
<
roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
<
providers>
<
clear/>
<
add name="AspNetWindowsTokenRoleProvider" applicationName="/" type="System.Web.Security.WindowsTokenRoleProvider" />
</
providers>
</
roleManager>
<
membership defaultProvider="ADMembershipProvider">
<
providers>
<
add name="ADMembershipProvider" applicationName="/" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" connectionProtection="Secure" />
</
providers>
</
membership>

Make sure your virtual or site is using Integrated Windows Authentication.

Done. Not a believer?

 Well, I kind of lied. If you are on XP, you really cant get this to work without hard coding a username and password for a domain user who has access to query LDAP into the membership provider (I guess that is how Microsoft defines secure by default, patch please) so change that guy to look like this:

<add name="ADMembershipProvider" applicationName="/" type="System.Web.Security.ActiveDirectoryMembershipProvider" connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName" connectionUsername="Domain\user" connectionPassword="securepassword" connectionProtection="Secure" />

Run your code, pop into a break point and type

Membership.GetUser() which will return a Membership user with a bunch of info about you, and try Roles.GetRolesForUser() will will get all of your roles or Roles.IsUserInRole("role") which will return true if you are in a role, false if you aren't or FileNotFound otherwise. (Just Kidding). You can add/remove roles etc.

BLAM! Winner! Between the membership and roles providers you can pretty much do anything you can do from the AD Users and Groups snap-in, all from the comforts of C#. 

Brought to you by the letters 'A' and 'D'

 

Published Mar 09 2007, 12:57 PM by Bob

Comments

 

Beaker said:

Just don't forget to properly setup you connection string :)

April 5, 2007 8:24 PM
 

Todd said:

Is there any way to get roles working with AD / forms authenticaiton?  The trouble begins when you want to use handhelds, Firefox, Linux or Macs.  We use a ASPNetDB database right now, but I'd rather do a lookup on AD through forms... any thoughts?

February 11, 2008 2:24 PM
 

kabonfootprint said:

nice.. great job... thanks

September 11, 2008 7:07 AM
 

rüya tabiri said:

thank you...

November 25, 2008 2:24 AM

Leave a Comment

(required)  
(optional)
(required)  
Add
Copyright © :: BlogByBob.com
Powered by Community Server (Non-Commercial Edition), by Telligent Systems