Click here to Skip to main content
Click here to Skip to main content

Eight steps to enable Windows authentication on WCF BasicHttpBinding

By , 9 May 2009
 

Table of contents

Introduction and goal

In this session, we will go through eight basic steps by which we can enable Windows authentication security on BasicHttpBinding. There are two types of security you can define in WCF: transport level and message level. In this article, we will discuss how we can define transport level security on BasicHttpBinding.

Nowadays I am distributing my 400 questions and answers ebook which covers major .NET related topics like WCF, WPF, WWF, AJAX, core .NET, SQL Server, architecture, and a lot more. I am sure you will enjoy this ebook: http://www.questpond.com/SampleDotNetInterviewQuestionBook.zip.

My other WCF FAQ articles

Step 1: Create a WCF project

Create a WCF service application project as shown in the below figure:

By default, the WCF project creates a class file which has the GetData function. This function takes in a number values and displays an explanatory sentence like ‘You entered 1 value’ when you enter ‘1’.

public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }
}

Step 2: Ensure authentication mode is Windows

When we create a WCF service application, it also has a web.config file associated with it. So open the web.config file and ensure that the authentication mode is Windows.

<authentication mode="Windows" />

Step 3: Define the binding in the web.config file

The third step is to define the bindings and the transport type. To define the bindings, we need to enter the basicHttpBinding element inside the bindings XML tag. We also need to define the clientCredentialType as Windows.

<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
.........
.........
</system.serviceModel>

Step 4: Bind the bindings with service interface

Now the bindings defined needs to be associated with a service interface, i.e., service1. So we need to modify the services elements as shown below. You can note that we have defined an end point which has the binding association.

<system.serviceModel>
........
........
........
<services>
<service behaviorConfiguration="WCFWindowsBasicHttpBinding.Service1Behavior" 
                       name="WCFWindowsBasicHttpBinding.Service1">
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="BasicHttpEndpointBinding"
name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</service>
</services>
.........
.........
.........
.........
</system.serviceModel>

Overall your <system.serviceModel> XML part as a whole with bindings and services is as shown below:

<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpEndpointBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="WCFWindowsBasicHttpBinding.Service1Behavior" 
               name="WCFWindowsBasicHttpBinding.Service1">
<endpoint address="" binding="basicHttpBinding"
bindingConfiguration="BasicHttpEndpointBinding"
name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WCFWindowsBasicHttpBinding.Service1Behavior">
<!-- To avoid disclosing metadata information, set the value below 
               to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below 
              to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Step 5: Ensure that anonymous access is disabled

Go to IIS properties and click on the Security tab and ensure that anonymous access is disabled and only Windows authentication is enabled.

Step 6: Host your WCF service on IIS

We need to host our service in IIS. Make the directory an IIS application so that your service can be hosted. Now if you try to browse the service, i.e., the SVC file, you will see that it pops up the authentication authorization security dialog box. So this service cannot be executed with Windows authentication.

Step 7: Consume the WCF service

Let’s consume the WCF service. Add an ASP.NET web application and do a add web reference. You will be popped up with a dialog box as shown below. Click on Add Reference so that a proxy is generated for the WCF service.

Step 8: Create the WCF client

Type in the following code snippet in your page load. Add the namespace reference and call the method GetData. The most important step to note is the credential supplied. DefaultCredentials passes the current Windows identity to the WCF service.

If you execute the service, you should get the following display as shown below:

You can try commenting the below code in your client, in other words we are not passing any credentials.

obj.Credentials = System.Net.CredentialCache.DefaultCredentials;

Now if you execute, you should get the below error stating that this is an unauthorized call.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Shivprasad koirala
Architect http://www.questpond.com
India India
Member

I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small
E-learning company in India. We are very much active in making training videos ,
writing books and corporate trainings. Do visit my site for 
.NET, C# , design pattern , WCF , Silverlight
, LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server  training 
and Interview questions and answers


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionServiceClient1 does not contain definition for CredentialsmemberMember 996489623 Apr '13 - 21:30 
I getting error "ServiceClient1 does not contain definition for Credentials" on this line of code
 
obj.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
what namespace do I need to use to use Credentials?
 
Swati
QuestionNot able to consume service after clientCredentialType is set to " Windows"memberMember 996489623 Apr '13 - 19:43 
I am not able to add service reference after   the   clientCredentialType is set to "windows". it is asking for user name and password. what should be provided?
 

Swati
AnswerRe: Not able to consume service after clientCredentialType is set to " Windows"memberMember 996489623 Apr '13 - 20:54 
Solved. I removed the mex Endpoint and now its accepting webreference
 
Swati
QuestionIs there a way to set the credentials through the config file?memberprogrammeranalyst2 Apr '13 - 11:49 
I have a client needing to connect to my WCF web service using Windows authentication. I have my client's code at hand and added the call: obj.Credentials = System.Net.CredentialCache.DefaultCredentials; which allowed them to connect.
 
However, can I get the same results through adding a configuration setting through their app.config? How can this be done? I really need this as they don't want to change their client code at all but would be willing to adjust the app config.
 
Essentially, they were using an old asmx service to call. I upgraded it to WCF using windows auth which was like the old asmx. Now, I would've hoped that they could've just changed their address line to point to the new service but are getting 401 Unauthorized error. Is there something I could do on my wcf side?
 
Thank You.
QuestionCode Not working in VS 2012membermeeram3913 Dec '12 - 22:47 
I tried this example in 2012. I was not getting the below code
obj.Credentials = System.Net.CredentialCache.DefaultCredentials;
Response.Write(obj.GetData(1,2));
 
Also, the authentication window is not popping up in systems where VS2012 installed. However, it gets fired in systems having VS 2010. Any suggestions pls?
Questionwell donememberVincenzo Malvone11 Dec '12 - 3:36 
Article clear and well done
QuestionVery nicemembersaikat Malakar9 Nov '12 - 1:32 
No words to express my feelings.
QuestionAuthntication not working if service added as Service Reference with BasicHttpBindingmemberSendilkumar.M22 Jun '12 - 2:38 
<pre lang="Text">If a WCF service with “BasicHttpBinding” and windows authentication added as service reference (instead of Web Reference),then will the authentication works?
I have created a test WCF service with Windows authentication and a Windows test application. Authentication works when WCF service has been referred as Web Service but not working when it is referred as Service Reference.
Is this the way it works?</pre>
 
M.Sendilkumar

QuestionBasicHTTPBindingmemberNilpesh29 May '12 - 20:31 
This binding use HTTP protocol. HTTP protocol not use transport layer or for minimum of time it use. So is it good to have Security defined on Transport Layer?
AnswerRe: BasicHTTPBindingmemberandrusha00713 Jul '12 - 4:51 
BasicHttpBinding can go as well through https..
QuestionPassing Windows credentials from from Client to Database through WCFmemberManjunathabe0114 Mar '12 - 23:35 
Hi Sir,I want to pass Client Windows credentials to WCF service , once its authenticated I want to pass same Client Windows credentials to Database for further operation. How can I achieve. Thanks in advance.
QuestionFacing one issue. [modified]memberrajwithu20 Dec '11 - 17:58 
Hi,
I have referred this article. I have one problem in this one. If we are using windows authentication then while browsing the service URL why it is asking for user name and password. why it is not taking my windows credentials default.

My web.config file settings are:

<system.serviceModel>
    <bindings>
      <basicHttpBinding>
        <binding name="netTcpBinding">
          <security mode="TransportCredentialOnly">
            <transport clientCredentialType="Windows" />
          </security>
        </binding>
      </basicHttpBinding>
    </bindings>
    <client />
    <services>
      <service behaviorConfiguration="WcfXMLExportService.XMLParsingBehavior"
        name="WcfXMLExportService.XMLParsing">
        <endpoint address="" binding="basicHttpBinding" bindingConfiguration="netTcpBinding" contract="WcfXMLExportService.IXMLParsing">
          <identity>
            <dns value="" />
          </identity>
        </endpoint>
        <!--<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />-->
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="WcfXMLExportService.XMLParsingBehavior">
          <serviceMetadata httpGetEnabled="true" />
 
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
 
Please give the solution to acheive this.

modified 3 Jan '12 - 8:08.

QuestionProduction Deployment?memberpravinpatkar14 Oct '11 - 11:10 
Nice Article, just like your others...
 
BTW I have 3 question,
 
What if I want to deploy these services to production environments that are load balancing?
Do I still need the following?



 
What if I want to AJAX enable these WCF services? (With "ScriptManager" & "enableWebScript")? Do I need to set anonymous auth on IIS for this?
 
What if these services are deployed inside custom SharePoint webapp (farm solutions)? Will the service configurations still remain the same?
 
Please answer these if possible. It will help me and others a lot and turn this article into a great one!
Thanks for listening... Cheers!
GeneralMy vote of 4memberEng. bipin24 Sep '11 - 2:29 
Really Good article , not only well written but describing every single point
Questionit is not working for WCF 4.0 and IIS 7memberVivek Shrivastava17 May '11 - 0:05 
Hi i tried and follow all step for WCF 4 and on window 7 machine . but configurtion is working but the userid and password pop-up is not comming. And also as per teh step 8 "Create teh WCF client", in place of obj.Credential Obj.Client credential is cooming which have only get property. please help me in that case. how i do same thing in window 7 machine.
GeneralSecurity settings not enabled for the IIS applicationmemberABlokha7727 Mar '11 - 20:27 
<title>Security settings for this service require Windows Authentication but it is not enabled for the IIS application that hosts this service.</title>
 
I've switched off anonymous access. The windows authentification is on.
GeneralSpeciifc Windows Id Authenticationmembermeatcp4 Mar '11 - 9:56 
Hi,
 
Is it possible that the client gets authenticated ONLY if it sends a specific Windows Username and Password?
 
In short, the service should not be allowed to be consumed by a client for just about any valid Windows Username and Password but for the one that it is expected to send.
 
J.
Generalit is not enabled for the IIS application that hosts this servicememberBMWABCD16 Sep '10 - 12:52 
I tried to run your code and get the following error:
System.NotSupportedException: Security settings for this service require Windows Authentication but it is not enabled for the IIS application that hosts this service
 
Do you know what I need to do for fixing this problem?
Thanks.

QuestionUnauthorized with client authentication scheme...memberPradeep Babu Yadagani8 Sep '10 - 9:11 
Hi,
 
I did exactly the same, as you explained. But I got below error...
 
"Metadata contains a reference that cannot be resolved: 'http://xxx/WebAuthTestService/MemberFinder.svc?wsdl'.
The WSDL document contains links that could not be resolved.
There was an error downloading 'http://xxx/WebAuthTestService/MemberFinder.svc?xsd=xsd0'.
The request failed with HTTP status 401: Unauthorized.
Metadata contains a reference that cannot be resolved: 'http://localhost/WebAuthTestService/MemberFinder.svc'.
The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was 'Negotiate,NTLM'.
The remote server returned an error: (401) Unauthorized.
If the service is defined in the current solution, try building the solution and adding the service reference again."
 
Interesting part is, I got this error while creating the service reference itself.
 
Can you plase help me in resolving this error.
 
Regards,
Pradeep.
QuestionSilverlight 3???membermarkbaer6 Jan '10 - 13:22 
I cannot set the Credentials in SL 3...is there another way to do it for Silverlight?
 
thanks
AnswerRe: Silverlight 3???memberrobalexclark15 Jan '10 - 1:58 
I have the same problem - it is not possible to set the credentials in silverlight
GeneralNot workingmemberbiopsy20 Nov '09 - 14:36 
I can execute web service methods with or without specifying credentials.
GeneralActive Directorymemberraranibar2 Jul '09 - 2:34 
This example only function with active directory?
GeneralHTTP 405: Method Not Allowed.memberraranibar1 Jul '09 - 13:31 
When I execute the programa I have this error
HTTP 405: Method Not Allowed.
in this code:
protected void Page_Load(object sender, EventArgs e)
{
Service1 obj = new Service1();
obj.Credentials = System.Net.CredentialCache.DefaultCredentials;
Response.Write(obj.GetData(1, true)); <<-- Here the error
}

GeneralErrormemberraranibar1 Jul '09 - 13:19 
Hi
 
I probe the example and I have a error I can't to do reference in my project asp.net when i chose "append reference web" i chose "service web in this solution" then I chose:
Service = Service1
Project = WCFWindowsBasicHttpBinding
Direcction url = Service1.svc
Then I have this error "the configuration this service require authentification windows but this disable for application IIS that hosted the service".
I probe in Windows Server2003 and Windows Vista Profeesional, I have framework 3.5 VS 2008
Please help me
 
Sorry for my enghish
 
Regards
Ricardo
GeneralRe: ErrormemberSancho Pancho27 Aug '09 - 5:58 
start->run-> iisreset
GeneralXML IndentationmemberDmitri Nesteruk20 May '09 - 21:42 
You might want to indent your XML to make it a bit easier to read.
GeneralExcellent article.memberM.K.A. Monster12 May '09 - 9:07 
Hi Shivprasad,
 
I'm referring to this article in one of my blog posts. I'm combining your knowledge with Silverlight.
 
Silverlight using WCF with Windows Authentication: http://mark.mymonster.nl/2009/05/12/silverlight-using-wcf-with-windows-authentication/[^]
 
Thanks for your article.
 
-
Mark Monster
GeneralGood Stuff.memberRene Pilon9 May '09 - 8:38 
Got my 5. Wink | ;)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 10 May 2009
Article Copyright 2009 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid