How To - Use SQL Role Provider with Windows Authentication in WCF calling from Windows Forms

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

Applies to

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

Summary

This How To article walks you through the process of using Windows authentication over wsHttpBinding to authenticate your users against a Microsoft SQL Server Roles 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 Roles 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 SQL Role Provider
  • Step 3 – Grant Access Permission to WCF Service Process Identity
  • Step 4 – Enable and Configure 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 WCF Service Reference to the Client
  • Step 9 – Test the Client and WCF Service
  • Additional Resources

Objectives

  • Configure the SQL Server Roles Provider to use 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 Roles provider. The netTcpBinding offers improved performance over an HTTP binding. Since IIS 6.0 cannot host a TCP binding, this how to 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 create a new WCF service and you will set the clientCredentialType attribute to Windows on the netTcpBinding in order to configure the WCF service to use Windows authentication. You will create a new Windows service and configure it to host your WCF service. You will then install a certificate on the server and configure it for WCF so that messages sent between 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 allow the WCF process identity to have access. 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 SQL Role Provider
  • Step 3 – Grant Access Permission to WCF Service Process Identity
  • Step 4 – Enable and Configure 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 WCF Service Reference to the Client
  • Step 9 – Test the Client and WCF Service

Step 1 – Create a WCF Service with Windows Authentication

Create a WCF service using netTcpBinding with Windows Authentication and Transport Security.
  1. Create a sample Windows service in Visual Studio 2008 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 mexTcpBinding 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.

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 SQL 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
  • -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 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 Windows Server 2003, the NT AUTHORITY\Network Service account is used by default to run WCF Service.

To grant database access
  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 you can run 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 Role Provider

In this step you will configure the use of the 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, 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, else the changes might get lost during executing the following steps.
  2. Right click on the Web.config file of the WCF Service and choose the option, Edit WCF Configuration...
  3. 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.
  4. In the configuration editor, expand the Advanced node, then expand the Service Behaviors folder.
  5. Select the default behavior created "ServiceBehavior".
  6. In the Behavior: ServiceBehavior section, click the Add button.
  7. In the Adding Behavior Element Extension Sections dialog box select serviceAuthorization and click Add button.
  8. In the Configuration section select serviceAuthorization option, under Service Behaviors.
  9. Set the principalPermissionMode attribute to UseAspNetRoles choosing from the drop down.
  10. Set the roleProviderName attribute to “MySqlRoleProvider” which you created above.
  11. On the configuration editor dialog, go to the File menu and select Save.
  12. In Visual Studio, verify your configuration. The configuration 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 will 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 you can run 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 don’t 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 will provide authorized access to the GetData method only for users in the Managers role
  1. Open the Service.cs file and add statement for using the System.Security.Permissions namespace

using System.Security.Permissions;
  1. Add the PrincipalPermissionAttribute to authorize users on 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, create a Windows Form application to test WCF Service.
  1. Right-click your Solution, click Add and then click New Project.
  2. In the Add New Project dialog box, select Windows Application from the Templates section.
  3. In the Name field, type Test Client and click Ok button. It will create a windows forms application.

Step 8 – Add WCF Service Reference to the Client

In this step, you add a reference to your WCF Service.
  1. Right-click your Client project and select 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 click the Go button
  3. In the Namespace field, change ServiceReference1 to WCFTestService and Click Ok button.
  4. In your Client project, a reference to WCFTestService should appear beneath Service References.

Step 9 – Test the Client and WCF Service

In this step you access the WCF Service and make sure it authorizes the users correctly.
  1. In your Client project, drag a Button control to your Form.
  2. Double-click the Button control to show the code behind.
  3. In the code behind of the button click, create an instance of the proxy; pass the credentials of a user with Managers role created in step 10, and call 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 on the Client project and select Set as Startup Project
  2. Run the Client application using F5 or Ctrl+F5, when you click the Button on the form it should display a message “You entered: 123
  3. Now test the application by passing the credentials of a user belonging to a different role (e.g., Employee) and you should receive Access Denied, a security exception. This is because the GetData operation is accessible only by the users who belong to Managers role.

Additional Resources

Contributors and Reviewers

  • External Contributors and Reviewers:
  • Microsoft Consulting Services and PSS Contributors and Reviewers:
  • Test team: Rohit Sharma, Chaitanya Bijwe, Parameswaran Vaideeswaran.
  • Edit team: Dennis Rea.
  • SEO team: Rob Boucher.

Last edited Mar 28, 2008 at 11:32 PM by prashantbansode, version 5

Comments

No comments yet.