Monday, September 5, 2011

WCF Exception "The login is from an untrusted domain and cannot be used with Windows authentication."

Today, when I was trying to test a WCF web service from a test harness application, I faced an exception "The login is from an untrusted domain and cannot be used with Windows authentication.".

My WCF service is a simple web service that will query a MSSQL database using Windows Authentication and return a collection of object to the caller. The service is hosted locally at my development machine IIS, while the MSSQL server  is at a different development server. Both are from same domain. After searching through the web for some times, I came through a blog post at here http://blog.mustoverride.com/2009/03/wcf-impersonation.html which exactly solved my problem. Credit to the author and thanks for the explanation.

From my understanding, the solution is quite straight forward. Basically, we need to:
1. Make sure the IIS user has the sufficient rights to access the database server or database.
2. Configure WCF to run in ASP.NET compatibility mode by setting aspNetCompatibilityEnabled property to true in WCF config file.
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
3. Impersonate the user in IIS from our WCF by adding identity tag in WCF config file:
<system.web>
<identity impersonate="true"/>
4. In WCF Service Contract implementation class, add the following statements to "activate" your WCF to run in ASP.NET compatibility mode:
Imports System.ServiceModel.Activation


<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)> _
Public Class MyService
    Implements IMyService

However, this problem only happened in my local development machine. When I tried to host the application in a web server and consumed it, there was no problem at all! So, this solution is to serve as a guide for those who need to test and debug their WCF web service at their own development machine.

Once again, thanks to the author for the great post. =)