WCF Using Windows Authentication and SqlRoleProvider over basicHttp

This tutorial is about building a sample WCF Service that makes use of  Windows(Active Directory) as Authentication mechanism and SQLRoleProvider for the Authorization.

1. Lets start by creating a new WCF Service Application. Open VS2010, File New Project under WCF select WCF Service Application. For the name just use the default: WcfService1.

2.  New Project was created, Go to the code of Service1.svc

The goal is: when a client application calls the GetData method, it should have a valid windows account (active directory account) and should be a member of a Role (SqlRole) that we will create later.

Press F6 to compile the project.

3. Next step is to configure service to use Windows and Sql Role Provider.

Right click web.config from WcfService1 project and select Edit WCF Configuration (if this is not available, Click Tools -> WCF Service Configuration Editor then close it, right click the web.config again the menu should be available)

WCF Configuration Editor Opens.

 

WCF Editor Step 1:  Create Service

In the Services Tab, click Create New Service.  In the service type, click Browse -> bin folder-> Select WcfService1.dll -> then Select WcfService1.Service1 then click Open.

Click Next, Contract should be WcfService1.IService1.

Click Next, for the communication mode select HTTP.

Click Next, for the interoperability select Basic Web Services interoperability.

Click Next, for the address type leave it empty, click Finish. New service was added:

Add BaseAddress, Go to Host -> In Base Address click New:  http://localhost:8000/WcfService1

 

WCF Editor Step 2:  Add Binding Configuration

In the Configuration Tab, go to Bindings -> Click New Binding Configuration, select basicHttpBinding from the list. Set the name to basicHttpBindingConfig.

Go to security tab set the following:

(General) Mode: TransportCredentialOnly

(TransportSecurityProperties) TransportClientCredentialType: Ntlm

Set the existing endPoint (basicHttp) to use the binding configuration that we just created.

To do this: go to Endpoints -> Click the first endPoint then on the general tab -> Endpoint Properties ->

Click Binding Configuration then select basicHttpBindingConfig.

 

 

WCF Editor Step 3:  Configure Service Behaviors

Go to Advance -> Service Behaviors

Modify the existing behavior and rename it to WcfService1.ServiceBehavior.

Click Add and select serviceAuthorization from the list.

Go to general Tab and set the ff:

PrincipalPermissionMode: UseAspNetRoles

RoleProviderName: WcfService1RoleProvider (we would configure this later on).

Update the service to use the service behavior. Go to Services -> WcfService1.Service1 in Behavior configuration select WcfService1.ServiceBehavior.

Click File -> Save.

4. After the WCF editor configuration next step is we need to configure the SQLRoleProvider.

SQLRoleProvider Step 1:  Create SqlRoleProvider database

Open Visual Studio 2010 command prompt and type the following command:

aspnet_reqsql -S {YourDatabaseServer} -E -A r

SQLRoleProvider Step 2:  Update Web.config

Copy and paste the following after configuration tag.

  <connectionStrings>
    <!–Setup Connection String for SQLRoleProvider –>
    <add name=”ASPNetDBConnString” connectionString=”Initial Catalog=aspnetdb;data source={YourDatabaseServer};Integrated Security=SSPI;”/>
  </connectionStrings>

Under system.web add the ff:

  <!–Setup Role Provider to be used for authorizations –>
    <roleManager enabled=”true” defaultProvider=”WcfService1RoleProvider” >
      <providers>
        <clear/>
        <add name=”WcfService1RoleProvider
             connectionStringName=”ASPNetDBConnString”
             applicationName=”WcfService1
             type=”System.Web.Security.SqlRoleProvider” />
      </providers>
    </roleManager>

Click File -> Save.

SQLRoleProvider Step 3:  Assign Roles to windows account

We will create a new role named: PowerUsers and only windows account that has this role will be able to execute the GetData method.

Execute the following script:

USE aspnetdb
GO

— Create a new role
EXEC aspnet_Roles_CreateRole ‘WcfService1’, ‘PowerUsers’

— Assign Windows Account to a Role
EXEC aspnet_UsersInRoles_AddUsersToRoles ‘WcfService1’, ‘{YourDomain\YourUserName}‘, ‘PowerUsers’, 8

5. Last step is to implement the role-based security on GetData method.  Go to WcfService1 project and do the ff:

Add reference to: System.Security

Open Service1.svc code – > Add : using System.Security.Permissions

Update GetData method to:

 

Testing:

For the testing i created a console application that calls the webservice with the following code:

 WcfService1.Service1Client client = new WcfService1.Service1Client();
Console.WriteLine(“Data From server: ” + client.GetData(4));
Console.ReadKey();

 

Sample Output (Calling service with an active directory account that is member of PowerUsers role):

 Sample Output (Calling service with an active directory account that is not a member of PowerUsers role):

 To remove the active directory account from a specific role (PowerUsers), execute the following script:

EXEC [aspnet_UsersInRoles_RemoveUsersFromRoles] ‘WcfService1′,’Domain\ActiveDirectoryAccount’, ‘PowerUsers’

Asp.NET – ReportViewer Control not working on IIS7

We recently upgrade our webserver from II6.0 to IIS 7.5, everything works fine except the ReportingViewer control that renders the MSSQL Reporting in Asp.NET. It shows a blank page with missing icons in IE 6.0 and displays missing resource on FireFox.

To solve the problem, you need to add a new Manager Handler in IIS Manager.

Steps are as follows:

1. Open IIS -> Go to Sites – > {Your WebSite} -> In the IIS section double click Handler Mappings

Handler Mappings in IIS7

2.  On the Action (Right side) click Add Managed Handler and set the ff. properties to:

Request Path: Reserved.ReportViewerWebControl.axd

Type: Microsoft.Reporting.WebForms.HttpHandler

Name: ReportViewerWebControl

Click Ok.

Should be fixed now.

 

 

 

BizTalk WCF Publishing – Configuration Errors

I have installed BizTalk Server 2006 R2 on my Windows XP SP3 machine and trying to make the BizTalk WCF Publishing work. Publishing went fine but when I tried to access the service using the url location (recieve port location) I was plagued with errors.

Error  # 1:

Failed to access IIS metabase.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.Hosting.HostingEnvironmentException: Failed to access IIS metabase.

The process account used to run ASP.NET must have read access to the IIS metabase (e.g. IIS://servername/W3SVC).

 Solution :

1. Go to Event Log  in the Application Logs there should be a warning log about ASP.NET.   Go to process information and get the account name:

Process information:

Process ID: 7472

Process name: aspnet_wp.exe

Account name: {AccountName}           

 2. Open command prompt, then type:

aspnet_regiis -ga {AccountName}

probelem 1 solved.

Error  # 2:

The Messaging Engine failed to register the adapter for “WCF-BasicHttp” for the receive location “/RPaulo/TestService.svc”. Please verify that the receive location exists, and that the isolated adapter runs under an account that has access to the BizTalk databases.

Solution:

Looking at the event log I see that the user account for ASP.NET is trying to connect to BizTalkMgtDb

An attempt to connect to “BizTalkMgmtDb” SQL Server database on server “RPauloBts” failed.

Error: “Login failed for user ‘RPauloBts\ASPNET’.”

Quickest fix is to add the ASPNET account to both BizTalk Application Users and BizTalk Isolated Host Users.

Everything should be ok now.

Visual Studio 2010 (VS2010) – Project Conversion Errors

I recently converted existing solution using VS2008 to VS2010 successfully but during the recompilation I’ve encountered two errors.

Error# 1:

Cannot import the following key file: {keyFile.pfx}. The key file may be password protected. To correct this, try to import the certificate again or manually install the certificate to the Strong Name CSP with the following key container name: VS_KEY_B652311015D642D5 

Solution:

            – Open command prompt and go to location of pfx file then type:

sn -i {keyFile.pfx} {VS_KEY}   //Ex: sn -i rpaulo.pfx VS_KEY_B652311015D642D5 

Error# 2:

The KeyContainer path ‘VS_KEY_B652311015D642D5’ is invalid. KeyContainer must point to an existing file.

Solution:  

In the folder wherein your project (.csproj)  is located create an empty file with fileName = missing VS_KEY.

BizTalk Configuration – Failed to connect to SQL database SSODB on SQL Server

I’m trying to install BizTalk 2006 R2 Developer edition on my machine and encountered this error:

Failed to connect to the SQL database SSODB on SQL Server ‘localhost’. (SSO).

So the first thing I check is whether indeed there’s a valid connection and permission to my local db.

Took me another 10 mins of googling and found this solution:

1. Go to C:\Program Files\Common Files\Enterprise Single Sign-On folder then type in

2. regasm SSOSQL.dll

Tried it again and error is gone..