Using Forms Authentication with Membership Providers in ASP.NET 2.0
 
Published: 09 Jun 2008
Abstract
This article examines the usage of Forms Authentication with Membership Providers using ASP.NET 2.0 in a series of parts. After providing a detailed overview of the concepts, Sudeep demonstrates setting up ActiveDirectoryMembershipProvider, ActiveDirectoryMembershipProvider with Active Directory Application Mode, and the usage of SqlMembershipProvider and SQL Role Provider in a step-by-step manner with the help of sample code listings. In addition to these, he also enlists the use of AuthorizationManager with Active Directory Membership Provider.
by Sudeep G
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 72658/ 148

Introduction

It has been sometime since I wrote an article. I was away learning more on IIS 7. In the meantime, I was also spending some time writing samples in C# for ASP.NET. I like coding with C#. I think the language has a lot of power and grace. Today, I am going to write about step-by-step procedures to setup Forms Authentication using ASP.NET 2.0 Membership Providers. In my opinion, the providers are one of the greatest features of ASP.NET 2.0.

As you may know, forms authentication is especially useful when you want to authenticate a user from the internet. In the previous versions all of the coding against the authentication store needed to be done by the developer himself. Microsoft has made this easier by providing membership providers that allow you to authenticate against commonly used authentication stores without any code. Keep in mind that these providers work for most cases, but you could still extend these classes and write your own provider.

The membership providers provide excellent abstraction for the web application with the underlying authentication store. The providers that are currently available are:

1. SqlMembershipProvider

2. ActiveDirectoryMembershipProvider

SqlMembershipProvider works against the Microsoft SQL Server databases. ActiveDirectoryMembershipProvider works against Microsoft Windows Active Directory and Active Directory Application Mode (ADAM). In this posting I want to show you how to accomplish the following:

1. Setting up ActiveDirectoryMembershipProvider.

2. Using AuthorizationManager (Azman) with these providers.

3. Touch up on Active Directory Application Mode.

4. Setting up and using SqlMembershipProvider.

To best test your scenarios, it will be really good to have a virtual setup of your own with a domain controller, a web server and a client machine. I setup 4 virtual machines to test these scenarios: A domain controller running Windows Server 2003 SP2, a web server running Windows Server 2003 SP2, Windows XP Pro SP2 and a Windows Server 2003 SP2 hosting SQL Server 2005 instance. I will mark out the places where you will need to make changes for your environment.

Ingredients: We need some basic ingredients to start that we can re-use. Also, I have tried to use as much default settings and minimal code possible so that much of the work is done by ASP.NET. I also explained the attributes that you can optionally configure. You can download these from the download link to start with.

·         Default.aspx

·         ManagementHome.aspx

·         Login.aspx

·         Web.config

 

Besides this, we need to configure the membership providers correctly to make this work. Configuring membership providers is easy. You need a Membership provider, a role provider and a SQL Connection string that is mapped to these providers. Besides these, there are a few attributes that are common to almost all membership providers.

1.    Name

2.    ApplicationName

3.    Type

Part 1: Setting up ActiveDirectoryMembershipProvider

Configuring & Setting up the application in Internet Information Services 6.0

Step 1: Add a connection string for connecting to the active directory

ASP.NET 2.0 introduced the <connectionStrings> configuration section that allows us to define all types of connection strings used by the application. It also includes a default connection string to use SQL Express edition. Open web.config and then locate <configuration>. Add a new line after this and add your connection string.

Listing 1

<connectionStrings>
<add 
connectionString="LDAP://test.mydomain.com/CN=Users,DC=test,DC=mydomain,DC=com" 
name="ADConnectionString" />
</connectionStrings> 

When I started, I wanted to know how to ensure that this connectionString was a valid one. Here is how I figured it out. Please note that this step assumes that you have read permissions to your Active Directory or you have a dedicated setup as I mentioned in the beginning. I installed Windows Server 2003 Support tools using the link in this KB article:

Windows Server 2003 Service Pack 1 Support Tools.

Run ADSIEDIT.MSC and under ADSI edit you can see your domain structure. Expand the first node in the tree. You should see something like: DC=test,DC=mydomain,DC=com. This is your last part of the LDAP connectionString. If you combine the values against “DC,” then you get your domain name, which will be test.mydomain.com – the first part of your connectionString. Now, all objects in active directory typically live under an OU (Organization Unit) or “CN.” If you expand the node DC=test,DC=mydomain,DC=com, then you will see either CN=Users or OU=User Accounts or something like this that contains your user accounts. By default, it falls into CN=Users. You can check with your network administrator or expand the OU/CN to locate the user accounts. Once you determine if they are part of or CN, then you can use that in your connection string. In my case when I expanded DC=test,DC=mydomain,DC=com, I found another node CN=Users that contained my user accounts. So I used it. Combining all the portions and then prefixing “LDAP://”, I got my connectionString, which is LDAP://test.mydomain.com/CN=Users,DC=test,DC=mydomain,DC=com.

Step 2: Add & configure your ActiveDirectoryMembershipProvider

Alright, now we have a connectionString and the next step is to configure your ActiveDirectoryMembershipProvider to use this connectionString. The <membership> element is a configuration that falls under <system.web>/<membership>. You can always refer to the schema settings at MSDN - that is the bible! Here is the link:

add Element for providers for membership (ASP.NET Settings Schema)

The membership provider must have certain attributes to be set. You can refer to the required attributes in the above link. In the description, it is indicated whether it is a required or an optional attribute. The two attributes that are absolutely required are name and type. The name attribute is used to uniquely identify the provider among a collection and used for its instance. The type specifies the type of a custom membership provider that that inherits the MembershipProvider abstract base class. So our provider configuration will look as follows:

Listing 2

<membership>
<providers>
<add name="MyADMembershipProvider" 
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, 
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" 
</providers>
</membership>

So, how do you get the value against “type”? You can refer to the GAC to get these. Make sure you pick the PublicKeyToken for the correct version of the framework you are using; in this case 2.0. Besides these, I also highly recommend that you configure the following optional attributes. If you wish to know why, please refer to the ASP.NET Settings Schema on MSDN. This is going to save a lot of pain during deployment.

·         applicationName

·         connectionStringName

·         connectionUsername

·         attributeMapUsername

Listing 3

<membership>
<providers>
<add name="MyADMembershipProvider" 
type="System.Web.Security.ActiveDirectoryMembershipProvider, System.Web, 
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" 
applicationName="FormsWithADAuth" connectionStringName="ADConnectionString"
connectionUsername="domain\username" connectionPassword="StrongPassword"
attributeMapUsername="sAMAccountName"/>
</providers>
</membership>

Step 3: Configure forms authentication in ASP.NET

Add the following under <system.web>.

Listing 4

<authentication mode="Forms">
<forms loginUrl="Login.aspx" name=".ADAUTH" slidingExpiration="false" timeout="5" />
</authentication>
<authorization>
<deny users=”?”/>
<allow users=”*”/>
</authorization>

So now we have wired these up as follows: Forms authentication (Uses) à Login Control (talks to) à MemberShipProvider (Uses) à specified connectionString.

Step 4: Configuring Application Settings in IIS

Forms authentication requires anonymous access enabled. The following are the steps to enable anonymous authentication in IIS 6.0.

1.    Open Internet Information Services Manager.

2.    Click Start, run and type “Inetmgr” without quotes and press ENTER.

3.    Expand the <ComputerName> node and then expand “Web Sites” node.

4.    Locate your website/virtual folder. Right click and select Properties.

5.    Select Directory Security tab.

6.    Under Authentication and access control, click the “Edit...” button.

7.    Ensure there is a check against “Enable anonymous access” and no other check boxes are checked.

8.    Click OK.

Setting up the application in Internet Information Services 7.0

I really love IIS 7. The new UI allows you to accomplish all of the above tasks from within the IIS manager.

Step 1: Configure Forms Authentication

1.    Open Internet Information Services Manager. Click Start, run and type “Inetmgr” without quotes and press ENTER.

2.    Expand the <ComputerName> node and then expand “Sites” node.

3.    Locate your website/virtual folder and click on it.

4.    Double click on the Authentication icon.

5.    Right click on Anonymous Authentication and select “Enable.”

6.    Right click on Forms Authentication and select “Enable.”

7.    Ensure that any other authentication status is “Disabled.”

8.    Right click on Forms Authentication and select Edit. Configure the following:

          Login URL: Login.aspx

          Authentication cookie time-out (in minutes): 5

          Name: .ADAUTH

          Protection Mode: Encryption and Validation

          Uncheck Extend cookie expiration on every request.

9.    Click on the Back button in IIS User Interface.

Step 2: Configure Authorization

1.    Double click the Authorization Rules icon

2.    In the Actions pane, click on Add Deny Rule...., then select “All Anonymous users” and click on the OK button.

3.    Click on the Back button in IIS User Interface.

Step 3: Configure Connection Strings

1.    Double click on the Connection Strings icon

2.    In the Actions Pane, click on Add...

3.    Configure the following:

Name: ADConnectionString

Click on Custom and then enter your connection string: LDAP://test.mydomain.com/CN=Users,DC=test,DC=mydomain,DC=com.

4.    Click OK.

5.    Click on the Back button in IIS User Interface.

Step 4: Configure ActiveDirectoryMembershipProvider

1.    Double click on the Providers icon

2.    From the Feature drop down, select .NET Users.

3.    In the Actions Pane, click on Add...

4.    From the Type dropdown, select “ActiveDirectoryMembershipProvider (System.Web.Security...).

5.    In the name box type “MyADMembershipProvider.”

6.    Under ConnectionStringName, select ADConnectionString.

7.    Under ApplicationName, provide a name for the application.

8.    Under Provider Specific Settings, click on the button “...” 

9.    Select each entry after connectionStringName and click on the Remove button.

10. Click on the Add button and for Name, provide: connectionUsername, value: domain\username.

11. Click on the Add button and for Name, provide: connectionPassword, value: Password.

12. Click on the Add button and for Name, provide: attributeMapUsername, value=sAMAccountName.

13. Click on the OK button.

14. Click on the Back button in IIS User Interface.

15. Open the application’s web.config and remove the attribute & value: PasswordFormat=”clear.”

NOTES:

The enablePasswordRetrieval attribute is not supported by ActiveDirectoryMembershipProvider. So remove this property.

PasswordFormat attribute will not be removed due to a bug. So you need to remove this manually.

Run the application and at the forms authentication login page, provide your username (not domain\username) and password and test if you get the home page/default.aspx page.

Part 2: Using AuthorizationManager (Azman) with Active Directory Membership Provider

Authorization Manager (AzMan) can be used along with ASP.NET to manage roles for the application and also check role membership. AzMan also has the capability of defining Tasks and operations on tasks against the AzMan policy store. I will be focusing more on role membership for ASP.NET applications.

Managing role membership is especially useful with AzMan because you can easily have the administrator add users to roles. This includes mapping Windows accounts to roles defined in AzMan. Therefore, it is helpful with ADAM and ActiveDirectoryMembershipProvider. AzMan can work with ADAM or use XML based policy store file that can be easily deployed along with the application. In the scenario I have below, I am going to use XML based policy store within the well known ASP.NET folder: App_Data.

AzMan is installed with Windows Server 2003 SP1 and later. For Windows XP clients, you need to install the Windows Server 2003 Administration Tools Pack, which you can download from the Windows Server 2003 Service Pack 1 Administration Tools Pack download page.

The first step to using AzMan is creating a policy store file. To do that, you need to run AzMan in “Developer Mode.” This allows creation of policy files and applications. In “Administrator Mode,” a system administrator can connect to the policy store and make the required changes.

Step 1: Create Policy Store File, Roles and assign the users

1.    Click Start, Run and type in AzMan.msc.

2.    Right click on Authorization Manager and select Options, then select Developer Mode. Click OK.

3.    Right click on Authorization Manager and select New Authorization Store...

4.    Select XML File then provide the path and name for the file in the Store name box. Eg: D:\<YourApplicationFolder\App_Data\Roles.xml.

5.    Right click on Roles.xml, select New Application..., and then provide a name for the application.

6.    Expand the Definitions folder and then right click on Role Definition...

7.    Provide a name for the role, Eg: Managers and click OK.

8.    Right click on Role Assignments and select New Role Assignment...

9.    Check the box against Managers and click OK. This role should now be listed under Role Assignments node.

10. Right click on Managers and Assign Users and Groups à From Windows and Active Directory...

11. Select the users that you want to be part of this group and click OK.

Step 2: Provide access permissions for the process account on the policy store

Open the policy file location and then add the process account to the ACL on roles.xml file. This will be NETWORK SERVICE by default on Windows Server 2003 and Local ASPNET account on Windows XP. If you changed the IIS application pool identity to a service account, then it should be that account.

Step 3: Configure the Role Provider and enable application to use Roles

Internet Information Service 6.0

Step 1: configure the Connection String for local policy store

Open your application’s web.config and add the following under <configuration> element.

Listing 5

<connectionStrings>
<add connectionString="msxml://D:\MyWebApp\App_Data\Roles.xml" 
name="LocalPolicyStore" />
</connectionStrings>

Step 2: Enable Role Manager and configure the role provider

Listing 6

<roleManager defaultProvider="FormsAuthRoles" enabled="true">
  <providers>
    <add applicationName="FormsWithADAuth" connectionStringName="LocalPolicyStore" 
   name="FormsAuthRoles" 
type="System.Web.Security.AuthorizationStoreRoleProvider, System.Web, 
Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </providers>
</roleManager>

Step 3: Configure Role based access for secured content

Create a folder under your application folder called “Secured” and copy the ManagementHome.aspx file into this folder. Then add a <location path="Secured"></location> just after </configuration> element and then add the access rule. It should look like this:

Listing 7

<location path="Secured">
  <system.web>
    <authorization>
      <allow roles="Managers" />
      <deny users="*" />
    </authorization>
  </system.web>
</location>

Internet Information Service 7.0

1.    Open Internet Information Services Manager. Click Start, run and type “Inetmgr” without quotes and press ENTER.

2.    Expand the <ComputerName> node and then expand “Sites” node.

3.    Locate your website/virtual folder and click on it.

4.    Double click on the Connection Strings icon.

5.    In the Actions Pane, click on Add...

6.    Configure the following:

7.    Name: LocalPolicyStore

8.    Click on Custom and then enter your connection string: msxml:// D:\<YourApplicationFolder\App_Data\Roles.xml.

9.    Click OK.

10. Click on the Back button in IIS User Interface.

11. Double click on the Providers icon

12. From the Feature drop down, select .NET Roles.

13. In the Actions Pane, click on Add...

14. From the Type dropdown, select “AuthorizationStoreRoleProvider (System.Web.Security...)."

15. In the name box type: “FormsAuthRoles.”

16. Under ConnectionStringName, select LocalPolicyStore.

17. Under ApplicationName, provide a name for the application.

18. Click OK.

19. Click on the Back button in the IIS User Interface.

20. Double click on the .NET Roles icon.

21. In the Actions Pane, click on Set Default Provider... and select FormsAuthRoles and click OK.

22. In the Actions Pane, click on Enable button.

23. Click on the Back button in IIS User Interface.

The IIS 7.0 manager only allows authorization rules with respect to IIS (new feature with IIS 7). For configuring authorization rules for ASP.net, we need to add the authorization rules under <system.web> section with a <location> tab, as illustrated below:

Listing 8

<location path="Secured">
  <system.web>
    <authorization>
      <allow roles="Managers" />
      <deny users="*" />
    </authorization>
   </system.web>
</location>

That is it! We are now ready to test our website. Logon with a user that is not part of the Managers Role in AzMan policy file and test if you can access the secured pages. Also test after adding that user to the Managers role.

One of the problems you will notice is that, after the user is added to the “Managers” role, the changes may not be visible immediately or until you recycle the worker process or restart the application. I am currently investigating where it caches this information and how to mitigate it.

Related Links

You can use the Windows Server 2003 Support Tools kit to figure this one out.

Support Tools Download

http://support.microsoft.com/kb/892777

add Element for providers for membership (ASP.NET Settings Schema)

How to authenticate against the Active Directory by using forms authentication and Visual Basic .NET

Part 3: Setting up ActiveDirectoryMembershipProvider with Active Directory Application Mode

Instead of using Azman, you could also use Active Directory Application Mode (ADAM). The benefit is that the ADAM instance and the web application can live on different machines.

Requirements: Windows XP Service Pack 1 or later; Windows Server 2003 Service Pack 1.

Install ADAM from: Active Directory Application Mode (ADAM) Download Page.

NOTE: Unfortunately, this is currently not supported on Windows Vista

The step-by-step details on how to setup ADAM are already on the Microsoft website. I have found this to be working and I will not repeat it here. Instead, here is the link to it: http://msdn.microsoft.com/en-us/library/ms998331.aspx .

Part 4: Setting up and using SqlMembershipProvider & SQL Role Provider

Setting up SqlMembership Provider is pretty easy. As a required ingredient, you definitely need an instance of SQL Server 2000 or above. SqlMembershipProvider works only with SQL Server. (SQL Express versions are also supported, but should not be used in production).

Step 1: Setup SQL Server database

Run the run Aspnet_regsql.exe found in the %systemroot%\Microsoft.NET\Framework\ v2.0.50727 to bring up the GUI configuration mode and choose to configure all ASP.NET Features. From the GUI, you can connect to a SQL Server instance running on another box by typing: SQLServerName\InstanceName. If you do not provide the instance name, it connects to the default instance.

Step 2: configure the Connection String for SQL Server store and roles store

Internet Information Services 6.0

Open your application’s web.config and add the following under <configuration> element.

Listing 9

<connectionStrings>
<add name="SQLConnection" connectionString="Data 
Source=DatabaseServer\Instance;Integrated Security=SSPI;Initial Catalog=aspnetdb;" />
</connectionStrings>
And under <system.web>
<roleManager enabled="true" defaultProvider="MySqlRoleProvider">
<providers>
<add name="MySqlRoleProvider" connectionStringName="SQLConnection" 
applicationName="SQLMembership" type="System.Web.Security.SqlRoleProvider, 
System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
    
<membership defaultProvider="SQLProvider">
<providers>
<add connectionStringName="SQLConnection" applicationName="SQLMembership"
enablePasswordRetrieval="false" enablePasswordReset="true" 
requiresQuestionAndAnswer="true"
requiresUniqueEmail="false" passwordFormat="Hashed" maxInvalidPasswordAttempts="5"
passwordAttemptWindow="10" name="SQLProvider" 
type="System.Web.Security.SqlMembershipProvider" />
</providers>
</membership>

Internet Information Services 7.0

1.    Open Internet Information Services Manager. Click Start, run and type “Inetmgr” without quotes and press ENTER.

2.    Expand the <ComputerName> node and then expand “Sites” node.

3.    Locate your website/virtual folder and click on it.

4.    Double click on the Connection Strings icon.

5.    In the Actions Pane, click on Add...

6.    Configure the following:

7.    Name: SQLConnection

8.    Click on Custom and then enter your connection string: Data Source=DBServer\Instance;Integrated Security=SSPI;Initial Catalog=aspnetdb;

9.    Click OK.

10. Click on the Back button in IIS User Interface.

11. Double click on the Providers icon.

12. From the Feature drop down, select .NET Roles.

13. In the Actions Pane, click on Add...

14. From the Type dropdown, select “SqlRoleProvider (System.Web.Security...).

15. In the name box type: “MySqlRoleProvider.”

16. Under ConnectionStringName, select SQLConnection.

17. Under ApplicationName, provide a name for the application.

18. Click OK.

19. Click on the Back button in the IIS User Interface.

20. Double click on the .NET Roles icon.

21. In the Actions Pane, click on Set Default Provider... and select MySqlRoleProvider and click OK.

22. In the Actions Pane, click on the Enable button.

23. Click on the Back button in IIS User Interface.

24. Double click on the Providers icon.

25. From the Feature drop down, select .NET Users.

26. In the Actions Pane, click on Add...

27. From the Type dropdown, select “SqLMembershipProvider (System.Web.Security...).

28. In the name box type: “SQLProvider.”

29. Under ConnectionStringName, select SqlConnection.

30. Under ApplicationName, provide a name for the application.

31. Click on the OK button.

32. Click on the Back button in the IIS User Interface.

So now we have wired these up as follows: Forms authentication (Uses) à Login Control (talks to) à MemberShipProvider & Role Providers(Uses) à specified connectionString.

Step 3: Test the Membership and roles using ASP.net Configuration

1.    From the Website Menu in VS 2005 or later, click on ASP.NET configuration.

2.    Click on the Security tab and click on Authentication type. Ensure it is set to “Internet.”

3.    Click on Create or Manage roles and then add the roles you want. Eg: Managers & Engineers. Once finished click the Back button in the bottom right corner of the page.

4.    Click on Create User and then add 2 users - one that has membership in Managers role and another one in Engineers.

5.    Run your application and login with one of your user accounts that you created in step 4.

Step 4: Test Roles

Create a folder called Secured under your application folder and create a new ASP.NET web page called Secured.aspx in that folder.

Add a hyperlink to this page from Default.aspx page.

Add the following location tag to your web.config:

Listing 10

<location path="Secured">
  <system.web>
    <authorization>
      <deny users="*"/>
      <allow roles="Managers" />
    </authorization>
  </system.web>    
</location>

Test with each user account to see if you can browse the secured page. Only the user with the Manager role will be allowed. Others should be redirected back to login page.

Downloads, References, and Conclusion

[Download Source]

References

SqlMembershipProvider Class

Conclusion

Hope this helped you better understand setting up using Membership providers with forms authentication, especially Active Directory Membership Provider with Authorization manager. Forms authentication is the default choice when it comes to authenticating users from internet and if those users are your domain users as well, combining these technologies can allow you to authenticate a user very efficiently without having to expose your active directory to public internet.

Please feel free to send me your comments and suggestions via the feedback link. I would most certainly appreciate it.



User Comments

No comments posted yet.

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2019 ASPAlliance.com  |  Page Processed at 2019-08-19 8:54:48 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search