WCF transportWithMessageCredential - vb.net

My experience with WCF is minimal so I'm sure I'm doing something wrong. But after hours of research I'm either not asking the right questions or I'm just old fashion stuck.
I have a windows form application (VB) with a service reference to a WCF WSDL that according to the WCF test application uses transportWithMessageCredential security.
When I attempt to connect to it I get badusernameOrPass every time. I've verified the credentials with the service operator so it's unlikely they are wrong.
Dim serviceProxy As New Provider.SubmissionServiceClient
serviceProxy.ClientCredentials.UserName.UserName = "user"
serviceProxy.ClientCredentials.UserName.Password = "pass"
Dim rtn2 = serviceProxy.ProcessSubmissionFromString(mystring)
Yields error:
System.ServiceModel.Security.MessageSecurityException
HResult=0x80131501
Message=An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail.
...
Inner Exception 1:
FaultException: There was a problem authenticating your username or password. BadUserNameOrPassword**
Does this methodology not work with that type of security or am I just missing an element or way off base?
Any help or insight would be appericated.

Credentials were incorrect. After quite a bit of back and forth they provided a fully qualified username that worked right away. The shortened version (without the domain) would work on their other systems but apparently their custom validator for this WCF services needed the longer username.
Had I been more confident in my WCF and skills in general I could have saved myself several hours of work and worry on deadline project.

Related

IncomingWebRequestContext.UriTemplateMatch null in WCF Service

I am trying to implement OAuth in a web service such as:
http://www.codeproject.com/Tips/372422/Secure-WCF-RESTful-service-using-OAUTH
Each time, when the Authenticate method is fire, WebOperationContext.Current.IncomingRequest exists, but UriTemplateMatch is null. This is even the case when using the WCF Test Client, so my client app isn't the problem. Ultimately, I need to access the QueryParameters under UriTemplateMatch.
In the Authenticate method, this is where the code breaks:
NameValueCollection pa = context.UriTemplateMatch.QueryParameters;
Looking for a different solution than this so everything is processed in one request:
https://stackoverflow.com/questions/7344478/using-the-wcf-http-web-api-uritemplatematch-is-always-null
Also, just as much as a solution, I am looking for a reason why the UriTemplateMatch would be null only in the case of a WCF Service. There are hundreds of articles on the presence of this problem, but I haven't found a good solution and/or explanation. I think I may be missing something in my web.config.
It seems that this solution is expecting incoming calls like :
http://localhost:49262/TestProject/Service.svc/user/123?oauth_consumer_key=key&oauth_nonce=10a33ed37b549301644b23b93fc1f1c5&oauth_signature=cUobFDxVB5wjPe9X2XICJ6awmnE%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1289976718&oauth_version=1.0
There are two ways to attach oauth parameters, one is through headers, another is through query string, both are valid, so I choose to attach oauth parameters in query string. There is not any problem to retrieve them from IncomingWebRequestContext.Headers if those oauth parameters are in headers
This solution is not from me. Check this link.

SecurityContext.Current not working, nullexception

im using a WCF service with the users and roles being kept in the database. In my service im trying to identify whose calling the service. So i type in my WCF service
string user = ServiceSecurityContext.Current.PrimaryIdentity.Name;
but i get i nullexception object not sent to an reference, ive tried googleing it all day but cant seem to find whats wrong. Any suggestions ?
"What's wrong" is that ServiceSecurityContext.Current is returning null rather than an instance of ServiceSecurityContext.
One scenario where this occurs is if the binding is configured to use Message security with MessageCredentialType set to None.
However, I'm not aware of any comprehensive documentation listing every scenario where ServiceSecurityContext.Current can be null: as the security context is established in the channel stack it is something which depends on the specific binding configuration and security providers in use. It could also, I imagine, be affected by custom Behaviors which fiddle with message properties.
Having said that, unless you have custom code inserted into the channel stack, it is probably a safe assumption that this will only occur in cases where the binding does not require any client authentication. You should check first of all that you are using a binding configuration which will auhenticate the client and provide the kind of user name IIdentity you are expecting.

I need my custom MembershipProvider to throw an exception on ValidateUser

I created a custom Membership Provider which is now working in production just fine validating my WCF calls.
I do have an issue every now and then that for some unknown reason my provider cannot validate the user. In those cases I do not want the ValidateUser function to just return false, so I thought of throwing and excception with a little more help (not too much, just a little).
My problem is, even though I am throwing a ProviderException the client always gets a MessageSecurityException with no helpful info... just the good old:
"An unsecured or incorrectly secured fault was received from the other party. See the inner FaultException for the fault code and detail."
with "An error occurred when verifying security for the message." in the Inner.
How can I get the message I am throwing in my own ValidateUser method? what about a custom behavior?
Thanks in advance
I found this post that led me to a solution, I'm not sure if it is the right move
Properly catch SecurityTokenException from a WCF UserNamePasswordValidator
Basically I have to throw a FaultException which I'm not really happy abou because my Membership Provider implementation is WCF agnostic (or at least was until now) now it knows about FaultExceptions :(
Is there a better solution out there?

WCF Getting "The primary signature must be encrypted." from FaultContract with ProtectionLevel.None

I have an existing asp.net application that talks to load balanced wcf services (iis hosted, in app pool running under account configured as servicePrincipalName, etc.). The wcf services return a few custom faults, all defined with FaultContract(typeof(x), ProtectionLevel = ProtectionLevel.None) -- these services are not exposed to the public. The client uses the 'service reference' generated classes to access the services.
This has worked fine but now, with the latest code base, we are getting "The primary signature must be encrypted." exceptions on the client when the service returns one of these faults. The service code and configuration is unchanged (at least the legacy parts that generate the faults). The client side service reference generated code appears the most changed (it often gets removed and recreated).
The security configuration is unchanged for over a year. All the updates are pretty current. We've tested this in three environments and as soon as we deploy the new code base, the faults start generating exceptions. Seems like it has to be in the generated classes but they are generated by Visual Studio so it is very perplexing.
Does this sound familiar to anyone? Any suggestions?
Update: Removing the ProtectionLevel attribute and allowing it to default makes the problem 'go away', but I am curious why specifying None causes it to fail. Perhaps it conflicts with the default level of the operation contract or service contract, but those values have not changed in the past year so that doesn't explain why what had worked now doesn't.
Update: For what it is worth, this change in code gen happened between 2.0.50727.3053 and 2.0.50727.3082 (according to the runtime-version comment in the generated code).
I haven't experienced this problem myself, but my questionn is: why on earth do you specify a "ProtectionLevel=None" in your fault contract? Any particular reason for that?
If not, I'd strongly recommend not specifying that at all - the default is ProtectionLevel=EncryptAndSign and that's usually your best bet all around. Try it, unless you have a very strong and explicit reason against it.
Marc

WCF, Custom Membership Provider and HttpContext

Ok, Im really going to show my stupidity regarding the ASP.NET security model here but here goes.
I have a WCF web service and I have managed to hack my way around to having it pipe through my custom membership provider.
My membership provider overrides "ValidateUser" in which I attempt to load a user object with data from our SQL server instance. All good so far, I retrieve the creds, load the users object and return true if I don't hit any bumps in the road.
At this point, I would usually stuff the user object (or id) into session or actually just some state bag that's accessible for the lifetime of the request. The problem that I am hitting is that HttpContext is null at this point, even though Im using ASP compatability attributes.
What other options do I have at hand?
Cheers, Chris.
EDIT:
Just to clarify what I want to do. I want to pass user credentials to be authenticated on the server, and once this has happened I would like to keep the the details of the authenticated user somewhere that I can access for the lifetime of the service request only. This would be the equiv of Http.Current.Items?
Is there any object that is instantiated per-request that I can access globally via a static property (i.e. in a similar way to HttpContext.Current)? I assumed that OperationContext was the this, but this is also null?
Can this really be such an uncommon problem? Send creds > retrieve user > stuff user somewhere for access throughout processing the request. Seems pretty common to me, what am I missing?
Cheers, Chris.
Basically, with WCF, the preferred best practice solution is to use per-call activation, e.g. each new request / call gets a new instance of the service class, and all the necessary steps like authentication and authorization are done for each request.
This may sound inefficient, but web apps, and in particular web services, ought to be totally stateless whenever possible. Putting stuff in a "state bag" just calls for problems further down the road - how do you know when to invalidate that cached copy of the credentials? What if the user exists your app but the cookie stays on his machine?
All in all, I would strongly suggest trying to get used to the idea of doing these step each and every time. Yes, it costs a little bit of processing time - but on the other hand, you can save yourself from a lot of grief in terms of state management in an inherently stateless environment - always a kludge, no matter how you look at it....
If you still insist on that kludge, you can turn on an ASP.NET "compabitility" mode for WCF which should give you access to HttpContext - but again: I would strongly recommend against it. The first and most obvious limitation is that this ASP.NET compatibility mode of course only works when hosting your WCF service in IIS - which I would again rather not do in production code myself.
To turn on the ASP.NET compatibility mode, use this setting in web.config:
<system.serviceModel>
<serviceHostingEnvironment
aspNetCompatibilityEnabled="true"/>
</system.serviceModel>
and you need to decorate your service implementation (the class implementing the service contract) with a corresponding attribute:
[AspNetCompatibilityRequirements(RequirementsMode=
AspNetCompatibilityRequirementsMode.Allowed)]
class YourService : IYourService
The AspNetCompatibilityRequirementsMode can be NotAllowed, Allowed or Required.
For more information and a more thorough explanation, see Wenlong Dong's blog post on ASP.NET Compatibility Mode