I am working on a Silverlight v3 web app and I would like to secure access to the WCF service I am using to fetch my data. I currently have the WCF working just fine, but it doesn't require any user credentials.
I'm not very experienced with this aspect of WCF, so my first idea was to add username and password parameters to each of my service's operations. The problem I have with this is that this would require a lot of redundant code, and the fact that the username and password would be transferred over the wire in plain text.
What I would like is a way to specify the credentials upfront on the client side right after I create my service proxy (I am using the proxy autogenerated from "Add Service Reference").
Upon googling for a solution to this, I could only find solutions that similar to my first idea (using username/password parameters). Could someone please point me in the right direction?
Thanks!
Where are these usernames and passwords coming from? If your web site already implements Forms authentication then you can bypass setting credentials yourself and use the forms authentication cookie. If your users are logged in then the cookie will travel with the web service call. In order to read it on the other side you need to make a couple of changes.
First you need to enable ASP.NET compatibility mode for WCF in the system.ServiceModel section:
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
Once that is done then for each service method you want to understand the ASP.NET cookie add the [AspNetCompatibilityRequirements] attribute to your service class
[ServiceContract]
[AspNetCompatibilityRequirements(
RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ExampleService
{
}
Now within each method you can access the HttpContext.Current.User.Identity object to discover the user's identity.
If you only want certain methods to be called by authenticated users then you can use a PrincipalPermission thus
[OperationContract]
[PrincipalPermission(SecurityAction.Demand, Authenticated=true)]
public string Echo()
As a bonus if you're using ASP.NET's role provider then those will also be populated and you can then use a PrincipalPermission on methods to limit them to members of a particular role:
[OperationContract]
[PrincipalPermission(SecurityAction.Demand, Role="Administators")]
public string NukeTheSiteFromOrbit()
And this works in Silverlight2 as well obviously.
Don't roll your own and add explicit parameters - that is indeed way too much work!
Check out the WCF security features - plenty of them available! You can e.g. secure the message and include credentials inside the message - all out of the box, no extra coding on your side required!
Check out this excellent article on WCF security by Michele Leroux Bustamante: http://www.devx.com/codemag/Article/33342
In your case, I'd suggest message security with user name credentials - you need to configure this on both ends:
Server-side:
<bindings>
<basicHttpBinding>
<binding name="SecuredBasicHttp" >
<security mode="Message">
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service name="YourService">
<endpoint address="http://localhost:8000/MyService"
binding="basicHttpBinding"
bindingConfiguration="SecuredBasicHttp"
contract="IYourService" />
</service>
</services>
And you need to apply the same settings on the client side:
<bindings>
<basicHttpBinding>
<binding name="SecuredBasicHttp" >
<security mode="Message">
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:8000/MyService"
binding="basicHttpBinding"
bindingConfiguration="SecuredBasicHttp"
contract="IYourService" />
</client>
Now your server and client agree on the security - on the client, you'd then specify the user name and password to use like this:
YourServiceClient client = new YourServiceClient();
client.ClientCredentials.UserName.UserName = "your user name";
client.ClientCredentials.UserName.Password = "top$secret";
On the server side, you'll need to set up how these user credentials are being validated - typically either against a Windows domain (Active Directory), or against the ASP.NET membership provider model. In any case, if the user credentials cannot be verified against that store you define, the call will be rejected.
Hope this helps a bit - security is a big topic in WCF and has lots and lots of options - it can be a bit daunting, but in the end, usually it does make sense! :-)
Marc
you can pass in some sort of authentication object and encrypt it at the message level with WCF. C# aspects (http://www.postsharp.org/) can then be used to avoid redundant logic. Its a very clean way of handling it.
Related
Some clients need to be able to connect to our WCF SOAP services using Basic authentication, while others need to use Windows authentication. We normally host our services in IIS, although we do provide a less-developed Windows Service hosting option.
It's my understanding that it is not possible to configure one endpoint to support both Basic and Windows authentication. So we have two endpoints per service.
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="BasicBinding" contract="SomeContract" bindingNamespace="http://www.somewhere.com/Something" />
<endpoint address="win" binding="basicHttpBinding" bindingConfiguration="WindowsBinding" contract="SomeContract" bindingNamespace="http://www.somewhere.com/Something" />
...
<bindings>
<basicHttpBinding>
<binding name="BasicBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Basic"/>
<message clientCredentialType="UserName"/>
</security>
</binding>
<binding name="WindowsBinding">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
<message clientCredentialType="UserName"/>
</security>
</binding>
</basicHttpBinding>
</bindings>
These are in the same Web Application in IIS. That Web Application has both Basic and Windows authentication enabled (else one of the above bindings wouldn't work).
When a client uses the Windows-authenticated endpoint (with "win" on the end of URL), this typically works fine. When the initial request doesn't contain any authentication information, a negotiation takes place between the client and IIS, they settle on Windows authentication and all goes well.
When a client uses the Basic-authenticated endpoint (without "win" on the end of URL), this works if they include the Authorization HTTP header with the correct encoded credentials in it. However, if they do not include any authentication information in the initial request, the negotiation ends up choosing Windows authentication. This gets the request past IIS security, but WCF then refuses the request, because it's going to a Basic-authenticated endpoint.
I am rather hazy on exactly what's happening in the negotiation. But it seems to me that IIS offers all authentication methods enabled for the Web Application (i.e. Basic and Windows), even though the particular WCF endpoint URL for the request only supports Basic.
I would like to know if there is anything we can do in IIS to make the negotiation come up with the right answer: that is, if the request is to a Basic-authenticated endpoint, tell the client to use Basic. Of course, we still want the negotiation to end up choosing Windows, when the request went to the Windows-authenticated endpoint.
If there isn't, then do you think we would be better off concentrating on our Windows Service-hosted version of the services? Or would that have similar problems somehow?
Final note: we do use Basic with HTTP for some internal uses, but we do know that this is an insecure combination. So we typically turn on HTTPS for production use; I've left that out here, for simplicity.
Yes, clientCredentialType="InheritedFromHost" solves the problem for me. This, new in .Net 4.5, means that one can now use the same endpoint URL for more than one authentication type. IIS settings control what authentication is allowed, meaning no longer possible to get IIS and WCF settings in conflict.
I know how to configure basicHttpBinding for NTLM authentication, but can't figure out a way to do the same for netTcpBinding.
Does netTcpBinding support NTLM? If so, how to force WCF service to use NTLM?
BTW a well known method using identity element for some reason didn't work at all. I am looking for something like this - clientCredentialType ="Ntlm" but for tcp.
Here is basicHttp setting:
<basicHttpBinding>
<binding name="BasicHttpBinding">
<security mode ="TransportCredentialOnly">
<transport clientCredentialType ="Ntlm"/>
</security>
</binding>
</basicHttpBinding>
Here is the comprehensive answer that I finally found, tested, and confirmed.
A. My WCF client used to build an EndPoint.Address dynamically as follow
EndPointAddress myEdpintAddress = new EndPointAddress(stringURL);
But in the case of a secure transport (net.tcp) it has to be initialized as follow
EndPointAddress myEdpintAddress = new EndPointAddress(new UrRL(string), myEndPointIdentity)
Without the EndPointIdentity parameters the Identity property in the EndPointAddress object is null, and generates the “...target principal name is incorrect... " error on the server side.
B. Our domain controller supports both Kerberos and Ntlm authentication. After above is done, generally there are four configuration scenarios on the client side for the net.tcp binding if security is other than “None”, and the WCF service runs as a domain account:
No <identity> elements in the client endpoint specified - WCF call fails
<identity> element provided, but with an empty value for dns, userPrioncipalName or servicePrincipalName elements - WCF call successful, but uses the Ntlm authentication
<identity> element provided with the a value for dsn or SPN – WCF call successfull; service uses Ntlm to authenticate.
<identity> element provided with the correct value for upn – WCF call successfull; service uses Kerberos for authenticate. Incorrect or missing value for upn trigger Ntlm authentication
Thanks.
The Net TCP Binding does not support "NTLM" as a client credentials type - you have a choice of None, Windows or Certificate only (see the MSDN docs on TcpClientCredentialType).
So in your case, try this:
<netTcpBinding>
<binding name="tcpWindows">
<security mode ="TransportCredentialOnly">
<transport clientCredentialType ="Windows"/>
</security>
</binding>
</netTcpBinding>
Any reason why this doesn't work??
Ok, I have seen several questions related to this issue, and I have tried a lot of the ideas presented in them with no success. Here's my situation:
I'm hitting a web service over my company's intranet. I have used svcutil.exe to generate the client class for WCF. I was able to run the web service call with no problem when the service was in development and did not require authentication credentials, so I know the code works. At the time, the code was running over SSL. I imported the required certificate into the Trusted Root Certification Authorities store, and everything was fine.
We just moved to a stage environment, and the service was upgraded to require credentials to connect. I switched my connection to the new endpoint, and added code to authenticate. This is my first time working with wcf, so please bear with me on any obvious mistakes. My problem is that I cannot locate the certificate via code to pass to the service for authentication. I am basing this off of some online code examples I found.
Here is an example of my config generated by svcutil:
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding
name="xxxSOAPBinding"
.... (irrelevant config settings)....
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport clientCredentialType="Certificate" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="https://xxxServices_1_0_0"
binding="basicHttpBinding" bindingConfiguration="xxxSOAPBinding"
contract="xxxService" name="xxxService" />
</client>
</system.serviceModel>
And here is the code I am using to try to connect. The exception is thrown as soon as I attempt to locate the certificate:
using (var svc = new xxxServiceClient())
{
svc.ClientCredentials.UserName.UserName = "XXX";
svc.ClientCredentials.UserName.Password = "XXX";
svc.ClientCredentials.ClientCertificate
.SetCertificate(StoreLocation.LocalMachine, StoreName.Root,
X509FindType.FindBySubjectName, "xxx");
...
}
I have tried several different X509FindTypes, and matched them to the values on the cert with no success. Is there something wrong with my code? Is there another way I can query the cert store to validate the values I am passing?
The dev machine where I am running Visual Studio has had the cert imported.
Two silly questions:
are you sure your certificiate is installed at all?
is this a certificiate specifically for this staging machine?
Also, it seems a bit odd you're first of all setting username/password, and then also setting the credential. Can you comment out the username/password part? Does that make any difference?
Marc
Are you sure the the certificate has been imported to the local machine store, it could be in the CurrentUser store.
This may sound stupid, but are you certain the new cert for the staging service has been installed into your cert store? That's most likely your problem.
Also, since you didn't mention what exception is thrown, it's possible the problem is that you've set username/password credentials before setting clientcertificate credentials, when your binding does not indicate the use of username/password. Could be a problem there; they're mutually exclusive, IIRC.
I've got a small WCF webservice working with the built-in WCF Service Host and with hosting by the Visual Studio 2008 built-in development webserver.
I these hosting enviroments I have relied on the WCF Test Client for invoking the service methods.
Now I am running into problems with my next phase of testing:
I have it hosted in IIS 5.1 on my WinXP dev machine and I think maybe the problem is I cannot continue to use WCF Test Client anymore. Here is what's happening:
Case 1: "Anonymous Access" is CHECKED (ENABLED)
WCF Test Client UI comes up properly, exposing the WebMethods and the INVOKE button.
Yet when I click INVOKE it fails to connect with a backend data store (a 3rd party product) that requires Windows authentication. I could post the error I get back from the product.DLL but I don't think it is relevant.
Case 2: "Anonymous Access" is un-CHECKED (DISABLED)
WCF Test Client UI fails to even initialize properly. My researching of this tells me that MEX (WS-Metadata Exchange) requires "Anonymous Access" and (apparently) WCF Test Client requires MEX. Here are key snippets of the error being returned:
Error: Cannot obtain Metadata from http://localhost/wcfiishost
The remote server returned an error: (401) Unauthorized.HTTP GET Error
URI: http://localhost/wcfiishost
There was an error downloading 'http://localhost/wcfiishost'.
The request failed with the error message:
Security settings for this service require 'Anonymous' Authentication but it is not enabled for the IIS application that hosts this service
The are lots of explanations of binding options, message security, etc. and stuff I honestly do not understand. Here is my take on where I am but I would love your opinions:
(a) Because I know my WCF webservice MUST be configured to use Windows Authentication, I conclude I cannot continue to use the WCF Test Client when hosting my service in IIS. That it has effectively outlived it's usefulness to me. I will just have to take the time to write a web client because WCFTestClient won't work without Anonymous.
(or)
(b) It is possible to use WCF Test Client if it and the hosted service are configured propertly (I just don't know what the special configuration techniques are for this).
Which is correct? Time to stop using WCFTestClient or is there a way to have it both ways? Thanks in advance for your advice.
EDIT: 11 June 09
Is there anything else I can provide to help someone else help me on this question?
I just tried to have the same setup - but in my case, everything seems to work just fine.
ASP.NET web site
WCF service, using basicHttpBinding without any special settings at all
IIS Application with anonymous = enabled and Windows authentication = enabled (both turned on)
I can easily connect to it with the WcfTestClient and retrieve the metadata, and I can then call it, no problem.
Inside my service function, I check to see whether the current user is a known user or not, it is correctly identified as a Windows authenticated user:
ServiceSecurityContext ssc = ServiceSecurityContext.Current;
if (ssc.IsAnonymous)
{
return "anonymous user";
}
else
{
if(ssc.WindowsIdentity != null)
{
return ssc.WindowsIdentity.Name;
}
if (ssc.PrimaryIdentity != null)
{
return ssc.PrimaryIdentity.Name;
}
}
return "(no known user)";
I don't really know, what more to check for (except I'm on Vista with IIS7). Any chance you could include this code to check for the user in your service code? Just to see....
Marc
Marc, your setup is not even close to Johns.
John uses WSHttpBinding that uses Windows Credentials for Message mode transport. The Windows Authentication isn't being used with BasicHttpBinding. Furthermore, John had AnonymousAuthentication disabled, which is why the Metadata Exchange (mex) is failing.
The call won't even reach inside the service side function, because we get a Error 401 (Unauthorized) when we try to call.
Just know John, I have the same issue, and I'm trying to somehow set up separate bindings per endpoint. Hopefully that will work.
When I set the title/subject of this question and reached a dead end here, I opened up the same issue in the MSDN forum with a different emphasis on the title (content of question essentially the same).
For me, the real issue was how to use WCFTestClient in IIS without Anonymous Authentication being set (because my service needed Integrated Windows Authentication only).
Mex apparently requires Anonymous and by default WCFTestClient seems to need Mex. The key seems to be accomodating both my doctoring up the web.config file carefully.
Anyway, I got it working with this web.config below (the MSDN link is here:
<?xml version="1.0"?>
<configuration>
<endpoint address=""
binding="wsHttpBinding"
bindingConfiguration="wsBindingConfig"
contract="sdkTrimFileServiceWCF.IFileService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="basic"
binding="basicHttpBinding"
bindingConfiguration="bindingConfig"
contract="sdkTrimFileServiceWCF.IFileService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding name="bindingConfig">
<security mode="TransportCredentialOnly">
<transport clientCredentialType="Windows"/>
</security>
</binding>
</basicHttpBinding>
<wsHttpBinding>
<binding name="wsBindingConfig">
<security mode="Transport">
<transport clientCredentialType="Windows"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
</serviceBehaviors>
</behaviors>
I have written a very simple WCF Service that sends and receives messages. I have tested the app through the VS 2008 default web server host and everything works fine. But when I deploy the WCF service to another computer's IIS I receive the following error:
"The request for security token could not be satisfied because authentication failed."
How can I set the authentication type to use my custom username and password in config file?
If it is not possible, please tell me how I can set its windows credentials because the 2 computers that I'm using, don't share the same users.
You need to turn off security for the binding. Otherwise, I believe that, by default, the wsHttpBinding will try to negotiate a Security Context Token (SCT).
So, modify the endpoint definition to point to a binding configuration section. Here's an example:
<endpoint address=""
binding="wsHttpBinding"
contract="HelloWorldService.IService1"
bindingConfiguration="TheBindingConfig">
And then add something like the following binding configuration right after the <services> section in the web.config's <system.serviceModel> section.
<bindings>
<wsHttpBinding>
<binding name="TheBindingConfig">
<security mode="None" />
</binding>
</wsHttpBinding>
</bindings>
Setting security to "None" is the key.
Hope this helped!
The above helped me - but what is not immediately obvious is how to add to the service end (its clear once you've done it what's needed, but not until you've done so). The reason its not entirely obvious is because there isn't a bindings section by default whereas there is liable to be one in the client.
So, just to be very clear - at the service end, add the bindings section (as detailed above) and then to the appropriate endpoint add the bindingConfiguration="TheBindingConfig" attribute. Obvious once you've done it once...
You don't actually need to turn off security and in some cases you shouldn't. Within a bindingConfiguration, you can specify message level security that does not establish a security context as follows:
<security mode="Message">
<transport clientCredentialType="Windows" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
algorithmSuite="Default" establishSecurityContext="false" />
</security>
Note the establishSecurityContext attribute. Both the client and service should have a security configuration with establishSecurityContext set to the same value. A value of true also works fine but false is recommended in an environment where the servers are load balanced.
Be sure to set this bindingConfiguration (specifying security mode 'none') on both client and server or else you will get this message - which is quite a red herring as far as debugging the problem.
The message could not be processed.
This is most likely because the action
'http://tempuri.org/IInterfaceName/OperationName'
is incorrect or because the message
contains an invalid or expired
security context token or because
there is a mismatch between bindings.
The security context token would be
invalid if the service aborted the
channel due to inactivity. To prevent
the service from aborting idle
sessions prematurely increase the
Receive timeout on the service
endpoint's binding.
If you are in debug mode then set the debug attribute as
<serviceDebug includeExceptionDetailInFaults="true"/>
by default it sets as false ..so while you go for debugging it throws that exception .
hope it helps .