Adding an custom authentication string to wcf - wcf

We are using an authentication string (guid) for client identification in our wcf services
and for database lookups.
We dont want to add this to every messagecontract.
Is there a way to do this in wcf?
Regards,
Rune

The best and typical way is to add this to a header in your WCF message - and that would be perfect in a message contract.
Why do you not want to add it to the message contract??
WCF typically encourages a "per-call" methodology - you send all necessary info with your call, each and every call that is. It is discouraged to have any kind of "state" that lingers around between calls.
So again: why not just include your authentication string as a header in every message? That's the preferred way of doing things these days.
UPDATE:
Check out Nicholas Allen's blog post on Adding Headers to a Call. Besides adding them to the message contract, you could also check out the Message Inspector sample he links to, which creates a message inspector that automagically adds those header entries to each outgoing call. No code clutter, no mess, nothing - just works.

Related

WCF Rest - what are the best practices?

Just started my first WCF rest project and would like some help on what are the best practices for using REST.
I have seen a number of tutorials and there seems to be a number of ways to do things...for example if doing a POST, I have seen some tutorials which are setting HttpStatusCodes (OK/Errors etc), and other tutorials where they are just returning strings which contain result of the operation.
At the end of the day, there are 4 operations and surely there must be a guide that says if you are doing a GET, do it this way, etc and with a POST, do this...
Any help would be appreciated.
JD
UPDDATE
Use ASP.NET Web API.
OK I left the comment REST best practices: dont use WCF REST. Just avoid it like a plague and I feel like I have to explain it.
One of the fundamental flaws of the WCF is that it is concerned only with the Payload. For example Foo and Bar are the payloads here.
[OperationContract]
public Foo Do(Bar bar)
{
...
}
This is one of the tenants of WCF so that no matter what the transport is, we get the payload over to you.
But what it ignore is the context/envelope of the call which in many cases transport specific - so a lot of the context get's lost. In fact, HTTP's power lies in its context not payload and back in the earlier versions of WCF, there was no way to get the client's IP Address in netTcpBinding and WCF team were adamant that they cannot provide it. I cannot find the page now but remember reading the comments and the MS guys just said this is not supported.
Using WCF REST, you lose the flexibility of HTTP in expressing yourself clearly (and they had to budge it later) in terms of:
HTTP Status code
HTTP media types
ETag, ...
The new Web API, Glenn Block is working addresses this issue by encapsulating the payload in the context:
public HttpResponse<Foo> Do(HttpRequest<Bar> bar) // PSEUDOCODE
{
...
}
But to my test this is not perfect and I personally prefer to use frameworks such as Nancy or even plain ASP NET MVC to expose web API.
There are some basic rules when using the different HTTP verbs that come from the HTTP specification
GET: This is a pure read operation. Invocation must not cause state change in the service. The response to a GET may be delivered from cache (local, proxy, etc) depending on caching headers
DELETE: Used to delete a resource
There is sometimes some confusion around PUT and POST - which should be used when? To answer that you have to consider idempotency - whether the operation can be repeated without affecting service state - so for example setting a customer's name to a value can be repeated multiple times without further state change; however, if I am incrementing a customer's bank balance this cannot be safely be repeated without further state change on the service. The first is said to be idempotent the second is not
PUT: Non-delete state changes that are idempotent
POST: Non-delete state changes that are not idempotent
REST embraces HTTP - therefore failures should be communicated using HTTP status codes. 200 for success, 201 for creation and the service should return a URI for the new resource using the HTTP location header, 4xx are failures due to the nature of the client request (so can be fixed by the client changing what they are doing), 5xx are server errors that can only be resolved server side
There's something missing here that needs to be said.
WCF Rest may not be able to provide all functionality of REST protocol, but it is able to facilitate REST protocol for existing WCF services. So if you decide to provide some sort of REST support on top of the current SOAP/Named pipe protocol, it's the way to go if the ROI is low.
Hand rolling full blown REST protocol maybe ideal, but not always economical. In 90% of my projects, REST api is an afterthought. Wcf comes in quite handy in that regard.

Action vs Reply action WCF

What's the use of action/reply action for service operation in WCF. So far, what I've understood is; action is used by WSDL to identify the service operation to which the message from the client belongs and in return reply action is used by service operation to identify the caller to which reply message belong --> Please correct me if I am wrong with this!
Now, I want to understand; what's the real use (apart from handling anonymous messages by using aster ix [*]), I mean this could well be handled internally by WCF instead of exposing it to the developer.
Also, why is action and replyaction required at all? I mean, we already have a name property for the service operation to identify the method and when I call Proxy.SomeMethod() then somemethod is already mapped to the Name property and it should be enough to identify the destination method for the message and similarly the replyaction. Please clarify.
Can I please get a simple real world scenario/or link to that to understand Action/ReplyAction in real life.
Many Thanks.
Actions are part of the various SOAP and WS-* specifcations.
So the first point is that this is not something unique to WCF it is a standard part of the specification you need to support if you want to have interoperable web services. They are used for message routing and other message handling functions.
Second, WCF DOES manage these by default. You only need to specify them yourself if you wish to customise or manage them in some other way. E.g. WCF will automatically generate them into the WSDL for you. WCF will also use them by default when it is selecting which operation to invoke for an incoming message. Again, WCF provides extension points to customise this behavior if you require.

How can I add a header/datamember to all DataContracts in a WCF service?

I am looking to extend existing services and add Authorization to every call being made. The problem I have is that I don't know how to do this in the best possible manner. What I need to do is to send the name of the module calling the WCF service. I already send the username and password for the service and now I need to extend that with the name of the module calling the service. This is because we might allow a user to open a module and display data from another module but not from a third.
If we would have used message contracts I would just add a MessageHeader for this and set that header when I create the request. That is unfortunately not an option with DataContracts so I was considering the following two alternatives.
Adding a DataMember in a base class with Order=1000 or something like that. I don't know what will happen if we add another DataMember before that though?
Create the property for the module name and set a header in the transport instead. Not really fond of this one though. It's pretty abstract and hard to follow.
Which one is the least evil or do you have a better suggestion?
EDIT 1: The problem is not how to send a header to the service the problem is how to send a header with a specific value to the server. In the message inspector I can only create generic instances with message.GetBody<DataContract>(); this means I have to know the type which I don't know how to.
EDIT 2: The issue here is that in our application we want to restrict access to a call based on from where the call is made so I need to pass this information. Let's say I make the call to MyService from FindUserModule then I need to add the id of that module in a header so that the AuthorizationManager can check if that user really should be authorized. This is due to service calls being used from many modules.
Handle this as SOAP header in custom message inspector.

WCF - how to add additional data to each call

I want to add a complex poco that will pass itself within each wcf call. Whats the bast practice for this case?
Typically, the best way to do something like this is passing such "meta-information" in a WCF header. You can easily create a message inspector to extend WCF (it's really not that scary and hard to do!) which would inject the POCO class (or what of it is necessary) into every outgoing request from the client, and retrieve it from the header and validate it on the server side.
There are a number of pretty good blog post out there showing you how to create a message inspector:
Richard Hallgren's WCF postings
Writing a WCF message inspector
Automatic Culture Flowing with WCF by using Custom Behaviour
Check out the two relevant interfaces to implement:
IClientMessageInspector on the client side, which has a BeforeSendRequest and AfterReceiveReply message to implement
IDispatchMessageInspector on the server side, which has a AfterReceiveRequest and BeforeSendReply method to implement
Here you go, check this out...
https://kinnrot.github.io/passing-complex-type-through-wcf/

WCF auditing/logging

I need to provide non repudiation in my WCF services and want to store all my incomming SOAP requests into a SQL server DB with signature/security data and all the envelope stuff.
This way, when a problem occurs, we can tell to the client "Hi, THIS is your signed message" exactly as you wrote it.
To do this, I need to store a relationship between the SOAP envelope XML's and my persisted bussiness objects/transactions.
Example: THIS is the SOAP Envelope used to add Customer ID=4567 to my Customers datables.
I need to establish a link between SOAP envelope and the bussiness transaction performed by my app. Storing ##identity of the logged message could be a solution. But, where do I put it? In the SOAP Body? Keep it in memmory?
I've reading about logging in WCF and wrote a Database Logger that inserts into tables the log info instead a text file, but i don't know how to link this data with the parsed/deserialized bussines datacontract object that arrives to my WCF service's method.
I don't even know if this is the rigth approach!
Any pattern/tip/hint/tool/help would be appreciated.
Thanks.
If you have enabled the message logging feature of WCF (http://msdn.microsoft.com/en-us/library/ms730064.aspx), you can write a custom listener, and there add all the logic you need. To write a custom listener you only have to implement the TraceListener interface (fairly simple) and then configure WCF to use it, adding it to the listeners section inside the system.diagnostics, replacing the default listener.