Thursday, July 26, 2012

Using WCF with windows authentication with an intranet ASP.Net website

You want to use windows authentication to protect a WCF service and the client is an ASP.Net intranet website (and has Windows Authentication turned on).

Create your WCF webservice website (I am assuming that the web-service website is different from the intranet website).

Enable Windows Authentication for the site.


For the purposes of testing create a service method that returns the user info:

public string GetUserInfo()         
             string userinfo = string.Empty;
             var windowsIdentity = ServiceSecurityContext.Current.WindowsIdentity;
             if (windowsIdentity != null)
                 userinfo = windowsIdentity.Name;
             return userinfo;        

Setup the web.config for the service so that the end point uses basicHttpBinding with a configuration where the security mode is set to “TransportCredentialOnly” and the Transport’s clientCredentialType is set to windows. Here is what it will look like:

       <service name="WcfService1.Service1">
         <endpoint address="Service1.svc" binding="basicHttpBinding" bindingConfiguration="basicHttpBindingConfiguration" contract="WcfService1.IService1" />
         <binding name="basicHttpBindingConfiguration">
           <security mode="TransportCredentialOnly">
             <transport clientCredentialType="Windows" />
           <serviceMetadata httpGetEnabled="true"/>
           <serviceDebug includeExceptionDetailInFaults="true"/>
     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />   </system.serviceModel>

Create your ASP.Net website (which will act as a client to your web-service). Set its authentication mode to “Windows” and make sure that you set "identity impersonate” to true.


Now add a reference to your web-service.

In your web.config make sure that the security mode is set to “TransportCredentialOnly” and the Transport’s clientCredentialType is set to windows. Here is an example:

         <binding name="BasicHttpBinding_IService1">
           <security mode="TransportCredentialOnly">
             <transport clientCredentialType="Windows"/>
       <endpoint address="http://xxxxxx/Service1.svc/Service1.svc"         binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IService1"         contract="ServiceReference1.IService1" name="BasicHttpBinding_IService1" />

That should be it. When you call “GetUserInfo”, you should get the name of the user that is accessing the asp.Net website.

No comments: