Wednesday, 21 November 2012

ASP.NET: How to use Active directory Role Manager

ASP.NET: How to use Active directory Authentication, Authorization, Membership & Role Provider/ Role manager
2 things need to be done for this job

  1. change the web.config file to connect to the active directory server and using the role provider class in step 2
  2. create a role provider class file in App_Code


Web.config:

<connectionStrings>
    <clear/>
    <add name="ADConnectionString" connectionString="LDAP://scc.local"/>
  </connectionStrings>



 <location path="About.aspx">

    <system.web>
      <authorization>
        <allow roles="ggStaff"/>
        <deny users="*"/>
      </authorization>
    </system.web>
  </location>



<compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.DirectoryServices.AccountManagement, Version=4.0.0.0, Culture=neutral,                      PublicKeyToken=B77A5C561934E089"/>
        <add assembly="System.DirectoryServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </assemblies>
    </compilation>



 <authentication mode="Forms">
      <forms name=".ADAuthCookie" loginUrl="~/Account/Login.aspx" timeout="2880"/>
    </authentication>
    <authorization>
      <allow roles="ggStaff"/>
        <deny users="*"/>
    </authorization>


<membership defaultProvider="MyADMembershipProvider">
      <providers>
        <clear/>
        <add name="MyADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web,  
                 Version=2.0.0.0, Culture=neutral,  PublicKeyToken=b03f5f7f11d50a3a"
connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName"
  connectionUsername="administrator"
connectionPassword="password"/>
      </providers>
</membership>



<roleManager enabled="true"
defaultProvider="ActiveDirectoryRoleProvider"
cacheRolesInCookie="true"
cookieName=".ASPXROLES"
cookiePath="/"
cookieTimeout="30"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
createPersistentCookie="false"
cookieProtection="All">
      <providers>
        <clear/>
        <add name="ActiveDirectoryRoleProvider" type="ActiveDirectoryRoleProvider"  
               connectionStringName="ADConnectionString" attributeMapUsername="sAMAccountName"            
               connectionUsername="administrator" connectionPassword="password"/>
      </providers>
</roleManager>




Creating a Active Directory role provider is pretty easy, all you have to do is:
  • create a new class  ActiveDirectoryRoleProvider.cs in App_Code folder and 
  • inherit RoleProvider: Just set the cursor to "RoleProvider", in the line: public class ActiveDirectoryRoleProvider : RoleProvider{} and a icon will come with option "Implement Role Provider"



References:
  • using System.Web.Security;
  • using System.Web.Configuration;
  • using System.Collections.Specialized;
  • using System.DirectoryServices;
  • using System.Globalization;
  • using System.Security;
Here's the the full code (minus the unimplemented inherited methods): public class ActiveDirectoryRoleProvider : RoleProvider { private string ConnectionStringName { get; set; } private string ConnectionUsername { get; set; } private string ConnectionPassword { get; set; } private string AttributeMapUsername { get; set; } public override void Initialize(string name, NameValueCollection config) { ConnectionStringName = config["connectionStringName"]; ConnectionUsername = config["connectionUsername"]; ConnectionPassword = config["connectionPassword"]; AttributeMapUsername = config["attributeMapUsername"]; base.Initialize(name, config); } public override bool IsUserInRole(string username, string roleName) { string[] roles = GetRolesForUser(username); foreach (string role in roles) { if (role.Equals(roleName, StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } public override string[] GetRolesForUser(string username) { var allRoles = new List<string>(); var root = new DirectoryEntry(WebConfigurationManager.ConnectionStrings[ConnectionStringName].ConnectionString, ConnectionUsername, ConnectionPassword); var searcher = new DirectorySearcher(root, string.Format(CultureInfo.InvariantCulture, "(&(objectClass=user)({0}={1}))", AttributeMapUsername, username)); searcher.PropertiesToLoad.Add("memberOf"); SearchResult result = searcher.FindOne(); if (result != null && !string.IsNullOrEmpty(result.Path)) { DirectoryEntry user = result.GetDirectoryEntry(); PropertyValueCollection groups = user.Properties["memberOf"]; foreach (string path in groups) { string[] parts = path.Split(','); if (parts.Length > 0) { foreach (string part in parts) { string[] p = part.Split('='); if (p[0].Equals("cn", StringComparison.OrdinalIgnoreCase)) { allRoles.Add(p[1]); } } } } } return allRoles.ToArray(); } }




No comments:

Post a Comment