How to: Use the ASP.NET Role Provider with a Service
The ASP.NET role provider (in conjunction with the ASP.NET membership provider) is a feature that enables ASP.NET developers to create Web sites that allow users to create an account with a site and to be assigned roles for authorization purposes. With this feature, any user can establish an account with the site, and log in for exclusive access to the site and its services. This is in contrast to Windows security, which requires users to have accounts in a Windows domain. Instead, any user who supplies his or her credentials (the user name/password combination) can use the site and its services.
The role provider feature uses a SQL Server database to store user information. Windows Communication Foundation (WCF) developers can take advantage of these features for security purposes. When integrated into a WCF application, users must supply a user name/password combination to the WCF client application. To enable WCF to use the database, you must create an instance of the ServiceAuthorizationBehavior class, set its PrincipalPermissionMode property to UseAspNetRoles, and add the instance to the collection of behaviors to the ServiceHost that is hosting the service.
To configure the role provider
In the Web.config file, under the <system.web> element, add a <roleManager> element and set its enabled attribute to true.
Set the defaultProvider attribute to SqlRoleProvider.
As a child to the <roleManager> element, add a <providers> element.
As a child to the <providers> element, add an <add> element with the following attributes set to appropriate values: name, type, connectionStringName, and applicationName, as shown in the following example.
<!-- Configure the Sql Role Provider. --> <roleManager enabled ="true" defaultProvider ="SqlRoleProvider" > <providers> <add name ="SqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="SqlConn" applicationName="MembershipAndRoleProviderSample"/> </providers> </roleManager>
To configure the service to use the role provider
In the Web.config file, add a <system.serviceModel> element.
Add a <behaviors> element to the <system.ServiceModel> element.
Add a <serviceBehaviors> to the <behaviors> element.
Add a <behavior> of <endpointBehaviors> element and set the name attribute to an appropriate value.
Add a <serviceAuthorization> element to the <behavior> element.
Set the principalPermissionMode attribute to UseAspNetRoles.
Set the roleProviderName attribute to SqlRoleProvider. The following example shows a fragment of the configuration.
<behaviors> <serviceBehaviors> <behavior name="CalculatorServiceBehavior"> <serviceAuthorization principalPermissionMode ="UseAspNetRoles" roleProviderName ="SqlRoleProvider" /> </behavior> </serviceBehaviors> </behaviors>