How To – Use the SQL Server Role Provider with Windows Authentication in WCF Calling from Windows Forms

- J.D. Meier, Carlos Farre, Jason Taylor, Prashant Bansode, Steve Gregersen, Madhu Sundararajan, Rob Boucher

Applies to

  • Microsoft® Windows Communication Foundation (WCF) 3.5
  • Microsoft Visual Studio® 2008
  • SQL Server

Summary

This How To article walks you through the process of using Windows Authentication over wsHttpBinding binding to authenticate your users against a Microsoft SQL Server™ Role Provider. The article shows you how to configure the Role Provider, configure WCF, and test the service with a sample WCF client. Use of the SQL Server Role Provider requires that you first set up and use the SQL Server Membership Provider.

Contents

  • Objectives
  • Overview
  • Summary of Steps
  • Step 1 – Create a WCF Service with Windows Authentication
  • Step 2 – Create a Role Store for the SQL Server Role Provider
  • Step 3 – Grant Access Permission to the WCF Service Process Identity
  • Step 4 – Enable and Configure the Role Provider
  • Step 5 – Create and Assign Roles to Windows Accounts
  • Step 6 – Implement Declarative Role-based Security
  • Step 7 – Create a Test Client
  • Step 8 – Add a WCF Service Reference to the Client
  • Step 9 – Test the Client and WCF Service
  • Additional Resources

Objectives

  • Configure the SQL Server Role Provider to use Microsoft Windows® accounts for authorizing users of the service.
  • Create a WCF service hosted in Microsoft Internet Information Services (IIS).
  • Expose the WCF service through netTcpBinding.
  • Call the service from a test client.

Overview

Windows authentication is suited for scenarios in which your users have domain credentials. In the scenario described in this How To article, users are authenticated against their Windows domain account and authorized against roles in the SQL Server Role Provider. The netTcpBinding binding offers improved performance over an HTTP binding. Because IIS 6.0 cannot host a TCP binding, the scenario described in this How To article instead hosts WCF in a Windows service. The WCF service with netTcpBinding can be consumed by a WCF-enabled .NET application through the use of a service reference. WCF transport security is used to support a secure communication channel in a point-to-point scenario. In general, you should always use transport security unless you need the additional flexibility that message security affords you. For example, you would use message security for scenarios in which there are intermediaries who need to inspect and re-route the message.

You will first create a new WCF service and set the clientCredentialType attribute to Windows on the netTcpBinding in order to configure the WCF service to use Windows Authentication. You will then create a new Windows service and configure it to host your WCF service. Next, you will install a certificate on the server and configure it for WCF so that messages sent between the client and server are encrypted. You will create a role store, populate it with roles, and map Windows accounts to these roles. You will then configure the role store to grant access to the WCF process identity. Finally, you will use the PrincipalPermissionAttribute in your WCF service code to specify which roles are allowed to access specific operations in your WCF service.

Summary of Steps

  • Step 1 – Create a WCF Service with Windows Authentication
  • Step 2 – Create a Role Store for the SQL Server Role Provider
  • Step 3 – Grant Access Permission to the WCF Service Process Identity
  • Step 4 – Enable and Configure the Role Provider
  • Step 5 – Create and Assign Roles to Windows Accounts
  • Step 6 – Implement Declarative Role-based Security
  • Step 7 – Create a Test Client
  • Step 8 – Add a WCF Service Reference to the Client
  • Step 9 – Test the Client and WCF Service

Step 1 – Create a WCF Service with Windows Authentication

In this step, you create a WCF service using netTcpBinding with Windows Authentication and WCF transport security.
  1. In Visual Studio 2008, create a sample Windows service by creating a project and selecting the Windows Service project template. Add an installer to the Windows service project so that it can be installed on the host machine.
  2. Create a sample WCF service in Visual Studio 2008 by creating a new Web site project and selecting the WCF Service project template.
  3. Modify the Windows service to host the WCF service by overriding the OnStart() and OnStop() methods to start and stop the WCF service within the Windows service.
  4. Configure the WCF service to use netTcpBinding with transport security by using the WCF Configuration Editor.
  5. Add a mexHttpBinding binding to the WCF service so that it can publish metadata. This interface will allow client applications to generate a proxy from the service definition.
  6. Install the Windows service by calling the installer from the command line using installutil.exe.

For more information on these steps, see “How To - Use netTcpBinding with Windows Authentication and Transport Security in WCF from Windows Forms” and follow steps 1 through 6.

Step 2 – Create a Role Store for the SQL Server Role Provider

The SQL Server Role Provider stores user information in a SQL Server database. You can create your SQL Server role store manually by using Aspnet_regsql.exe from the command line.
  • From a Visual Studio 2008 command prompt, run the following command.

aspnet_regsql -S .\SQLExpress -E -A r

In this command:
  • -S – Specifies the server, which is (.\SQLExpress) in this example.
  • -E – Specifies to use Windows Authentication to connect to SQL Server.
  • -A r – Specifies to add only the Role Provider feature.
  • For a complete list of the commands, run Aspnet_regsql /?

Step 3 – Grant Access Permission to the WCF Service Process Identity

Your WCF service process identity requires access to the Aspnetdb database. If you host the WCF service in Microsoft Internet Information Services (IIS) 6.0 on Microsoft Windows Server® 2003, the NT AUTHORITY\Network Service account is used by default to run WCF Service.
  1. Create a SQL Server login for NT AUTHORITY\Network Service.
  2. Grant the login access to the Aspnetdb database by creating a database user.
  3. Add the user to the aspnetRolesFullAccess database role.

You can perform these steps by using Enterprise Manager or by running the following script in SQL Query Analyzer:
-- Create a SQL Server login for the Network Service account
sp_grantlogin 'NT AUTHORITY\Network Service'

-- Grant the login access to the roles database
USE aspnetdb
GO
sp_grantdbaccess 'NT AUTHORITY\Network Service', 'Network Service'

-- Add user to database role
USE aspnetdb
GO
sp_addrolemember 'aspnet_Roles_FullAccess', 'Network Service'

Note:

Step 4 – Enable and Configure the Role Provider

In this step, you configure the use of the SQL Server Role Provider in your WCF service.
  1. In the web.config file, verify that you have a connection string similar to the following:
<connectionStrings>
  <add name="MyLocalSQLServer"
       connectionString="Initial Catalog=aspnetdb;
      data source=.\sqlexpress;Integrated Security=SSPI;" />
</connectionStrings>

  1. Add a <roleManager> element inside the <system.web> element as shown in the following example. Note the use of the <clear/> element, which prevents the default provider from being loaded and then never used.
...
<system.web>
  <roleManager *enabled="true"* defaultProvider="MySqlRoleProvider" >
    <providers>
      <clear/>
      <add name="MySqlRoleProvider"
           connectionStringName="MyLocalSQLServer"
           applicationName="MyAppName"
           type="System.Web.Security.SqlRoleProvider" />
    </providers>
  </roleManager>
</system.web>
...
  1. Save the Web.Config file; otherwise the changes might get lost during execution of the following steps.
  2. Right-click the Web.config file of the WCF service and then click Edit WCF Configuration. If you do not see the Edit WCF Configuration option, click the Tools menu and select WCF Service Configuration Editor. Close the WCF Service Configuration Editor tool that appears. The option should now appear on the web.config context menu.
  3. In the Configuration Editor, expand the Advanced node, and then expand the Service Behaviors folder.
  4. Select the default behavior "ServiceBehavior".
  5. In the Behavior: ServiceBehavior section, click the Add.
  6. In the Adding Behavior Element Extension Sections dialog box select serviceAuthorization and then click Add.
  7. In the Configuration section, under Service Behaviors, select serviceAuthorization.
  8. Set the principalPermissionMode attribute to UseAspNetRoles by choosing this option from the drop-down list.
  9. Set the roleProviderName attribute to “MySqlRoleProvider”, which you created above.
  10. In the Configuration Editor dialog box, on the File menu, click Save.
  11. In Visual Studio, verify your configuration, which should look as follows.
….
<behavior name="ServiceBehavior">
  <serviceMetadata httpGetEnabled="true" />
    <serviceDebug includeExceptionDetailInFaults="false" />
       ….
       <*serviceAuthorization* *principalPermissionMode="UseAspNetRoles" 
             roleProviderName="MySqlRoleProvider*" />
       ….
 </behavior>
….

Step 5 – Create and Assign Roles to Windows Accounts

In this step, you create roles for your application and assign users to those roles by executing SQL scripts to add them to the database directly.
  1. Create a new role, Managers, for your application.
  2. Add an existing Windows user to the Managers role.

You can perform these steps by using Enterprise Manager or by running the following script in SQL Query Analyzer.
USE aspnetdb
GO

-- Create a new role, called Managers
EXEC aspnet_Roles_CreateRole 'MyAppName', 'Managers'

-- Assign a windows user to the Managers role 
-- parameters <<Application name>>, <<User Name>>, <<Role Name>>, <<DateTime>>
EXEC aspnet_UsersInRoles_AddUsersToRoles 'MyAppName', 'Domain\userName', 'Managers', 8


Important: The application name should be the same name that is specified in the Role Provider configuration.

Note: If you do not have Enterprise Manager or Query Analyzer, you can use Microsoft SQL Server Management Studio Express, available at http://www.microsoft.com/downloads/details.aspx?FamilyID=c243a5ae-4bd1-4e3d-94b8-5a0f62bf7796&displaylang=en

Step 6 – Implement Declarative Role-based Security

In this step, you provide authorized access to the GetData method only for users in the Managers role.
  1. Open the Service.cs** file and add a statement for using the System.Security.Permissions namespace:

using System.Security.Permissions;
  1. Add the PrincipalPermissionAttribute attribute to authorize users in the Managers role with the SecurityAction as Demand to the GetData method:
[PrincipalPermission(SecurityAction.Demand, Role="Managers")]
public string GetData(int value)
{
	return string.Format("You entered: {0}", value);
}

Step 7 – Create a Test Client

In this step, you create a Windows Forms application to test the WCF service.
  1. Right-click your solution, click Add, and then click New Project.
  2. In the Add New Project dialog box, the Templates section, select Windows Application.
  3. In the Name field, type Test Client and then click OK.
A Windows Forms application is created.

Step 8 – Add a WCF Service Reference to the Client

In this step, you add a reference to your WCF service.
  1. Right-click your Client project and then click Add Service Reference.
  2. In the Add Service Reference dialog box, set the URL to your WCF service – for example, http://localhost/WCFTestService/Service.svc – and then click Go
  3. In the Namespace field, change ServiceReference1 to WCFTestService and then click OK.
A reference to WCFTestService should now appear beneath Service References in your Client project.

Step 9 – Test the Client and WCF Service

In this step, you access the WCF service and make sure that it authorizes the users correctly.
  1. In your Client project, drag a button control onto your form.
  2. Double-click the button control to show the underlying code.
  3. In the code behind the button click, create an instance of the proxy, pass the credentials of a user with Managers role created in step 10, and call the GetData operation of your WCF Service. The code should look as follows:
private void button1_Click(object sender, EventArgs e)
{
      WCFTestService.ServiceClient myService = new
                    WCFTestService.ServiceClient();
MessageBox.Show(myService.GetData(123));
      myService.Close();
}
  1. Right-click the Client project and then click Set as Startup Project.
  2. Run the Client application by pressing F5 or Ctrl+F5. When you click the button on the form, the message “You entered: 123” should appear.
  3. Test the application by passing the credentials of a user belonging to a different role (e.g., Employee) and you should receive the security exception Access Denied. This is because the GetData operation can be accessed only by users who belong to Managers role.

Additional Resources

Last edited Jun 12, 2008 at 12:48 AM by prashantbansode, version 1

Comments

No comments yet.