Is WCF result as JSON + unparseable curft needed for better security? How is it implemented? - wcf

I'm reading about this ajax response that describes ways to prevent Javascript based exploits.
Does it make sense to apply this technique to WCF-based services that return JSON?
How would this be implemented server side?
How would the client consume it?

There's one way WebScriptEnablingBehavior -- the behavior of choice if you want a WCF service that works with ASP .NET AJAX -- deals with this. By default, its response mode is "WrappedResponse". If you watch this in action using Fiddler, it means that every response from the service -- even a simple number -- will wrapped in {d:} wrapper as follows:
{ "d" : return-value }
On the other hand, WebHttpBehavior is XML out-of-the-box, but if you switch it to JSON, you can choose between WrappedResponse and BareResponse. WrappedResponse is similar to WebScriptEnablingBehavior (if I remember correctly), but BareResponse would be unsecure JSON transmitted back as a direct return value.

Related

Can Webapi be used in an application which is not excessed by any external application?

I'd read it somewhere that whenever one needs to do data intensive work then Webapi could be used. Ex: autocomplete textbox where we get data from using ajax on key press.
Now someone told me that Webapi shouldn't be used within applications which are not externally accessed. Rather action should be used to the same work as it is capable of returning the data back in a similar fashion to webapi.
I'd like to know your suggestions over it.
Depends on how you look at it. If all you need is ajax-ification of your controller actions, then you really don't need Web-API. Your actions can return a JsonResult and it is very easy to consume that from your client side through an AJAX call.
Web-API makes it easy for you to expose you actions to external clients. It supports HTTP protocol and Json and XML payloads automatically, out of the box, without you writing the code for it. Now, there is nothing preventing you from consuming the same Web-API actions from your own internal clients in an AJAX manner.
So the answer to your question depends on your design. If you don't have external clients, then there is no string need for you to have Web-API. Your standard controller actions can do the job.

Implementing versioning a RESTful API with WCF or ASP.Net Web Api

Assume i've read a lot about versioning a restful api, and I decided to not version the the service through the uri, but using mediatypes (format and schema in the request accept header):
What would be the best way to implement a wcf service or a web api service to serve requests defining the requested resource in the uri, the format (eg. application/json) and the schema/version (eg player-v2) in the accept header?
WCF allows me to route based on the uri, but not based on headers. So I cannot route properly.
Web Api allows me to define custom mediatypeformatters, routing for the requested format, but not the schema (eg. return type PlayerV1 or PlayerV2).
I would like to implement a service(either with WCF or Web Api) which, for this request (Pseudo code):
api.myservice.com/players/123 Accept format=application/json; schema=player-v1
returns a PlayerV1 entity, in json format
and for this request:
api.myservice.com/players/123 Accept format=application/json; schema=player-v2
returns a PlayerV2 entity, in json format.
Any tips on how to implement this?
EDIT: To clarify why I want to use content negotiation to deal with versions, see here: REST API Design: Put the “Type” in “Content-Type”.
What you are bringing here does not look to me as versioning but it is is more of content negotiation. Accept header expresses wishes of the client on the format of the resource. Server should grant the wishes or return 406. So if we need more of a concept of Contract (although Web API unline RPC does not define one) then using resource is more solid.
The best practices for versioning have yet to be discussed fully but most REST enthusiast believe using the version in the URL is the way to go (e.g. http://server/api/1.0.3/...). This also makes more sense to me since in your approach using content negotiation server has to keep backward compatibility and I can only imagine the code at the server will get more and more complex. With using URL approach, you can make a clean break: old clients can happily use previous while new clients can enjoy the benefits of new API.
UPDATE
OK, now the question has changed to "Implementing content-negotiation in a RESTful AP".
Type 1: Controller-oblivious
Basically, if content negotiation involves only the format of the resource, implementing or using the right media type formatter is enough. For example, if content negotiation involves returning JSON or XML. In these cases, controller is oblivious to content negotiations.
Type 2: Controller-aware
Controller needs to be aware of the request negotiation. In this case, parameters from the request needs to be extracted from the request and passed in as parameter. For example, let's imagine this action on a controller:
public Player Get(string schemaVersion)
{
...
}
In this case, I would use classic MVC style value providers (See Brad Wilson's post on ValueProviders - this is on MVC but Web API's value provider looks similar):
public Player Get([ValueProvider(typeof(RequestHeadersSchemaValueProviderFactory))]string schemaVersion)
{
...
}

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.

WCF service authentication method

I'm building a WCF SOAP service at the moment. I will, of course, need some authentication on the service.
Reading this very helpful blog post says that to use the built-in authentication points requires that the endpoint use the wsHttp binding.
This would be fine if I could guarantee that users would be communicating with the service through a client based on the meta-data exposed by WCF (basically, something like a client written in C# with a web service reference). However, I can't guarantee this!
I will still need to allow users to communicate with just raw (unencrypted) XML.
So, questions:
Does the wsHttp binding still allow for raw XML input?
If not, would I be wiser to
Implement two separate authetication points? One for raw XML input and one for encrypted input
Or
Allow input from wsHttp to fall back on some in-method validation that would be shared with the raw XML input?
Is it wise to allow users to pass their credentials inside a raw XML request?
EDIT: It sounds like I miscommunicated or misunderstood something in my original post, so here I will clarify what I mean by "raw XML".
By raw XML, I mean just the SOAP packet and the accompanying HTTP headers - as I might send from soapUI or Fiddler. As I understand it, messages over the wsHttp binding are encrypted when a client is generated from the WSDL (for example, in C#).
If this is not the case, then how would I go about attaching the same sorts of credentials to a raw XML (for want of a better term) request as I do a request run through a client? Are they attached as HTTP headers? XML elements in the SOAP envelope?
wsHttp is a SOAP binding, which means that your content gets wrapped in a SOAP envelope, possibly with headers relating to the message and various WS-* specifications being used.
I would ask why you need to support raw XML? Most platforms today support SOAP messaging and the whole idea of SOAP is to provide interoperability between different platforms. On most platforms it is as easy to develop a SOAP client as a raw XML client. In most cases, it is simply a case of taking the WSDL and generating a client. If you want to use standard facilities like authentication and message encryption then this is a much better way to go.
There are currently no hooks to do interoperable authentication for raw XML. You will have to come up with your own mechanism to do this and it will be non-standard. For your web service users, this means it will be probably entail more development effort than if you just went with SOAP.

Is it possible to implement a redirector / reverse proxy using RequestInterceptor from WCF REST Starter kit

I am attempting to implement a reverse proxy using the RequestInterceptor from WCF REST starter kit. I am able to set the basic header properties and configure the calls. I am getting stuck with the following aspects:
Returning an appropriate response - my webservice can return text+xml, image or json. I am not able to send the appropriate response type. The Message.CreateMessage overloads are all SOAP aligned i.e. they accept only Xml constructs, so I am not able to send either JSON or image streams. I need to convert them into XElements - I am definitely doing something wrong here.
I also want the reverse proxy to be functioning well in the presence of cookies, gzip/deflate and SSL.
Based on the above requirements, do you think it makes sense to do this using REST starter kit? The Requestinterceptor was fairly easy to plug into, however the rest of the code is driving me nuts.
There is a mapping between both JSON and arbitrary binary content to XML which is used in messages for WCF (see some examples at http://blogs.msdn.com/b/carlosfigueira/archive/2011/04/19/wcf-extensibility-message-inspectors.aspx), so you can use Message.CreateMessage to create non-XML messages as well.
Having said that, it's really not intuitive to do that in WCF as of now. The new libraries in the WCF Web API - http://wcf.codeplex.com - provide a very nice way of intercepting / redirecting / bypassing the WCF pipeline especifically for HTTP messages. Also, it support multiple formats in a native way (i.e., without need to do some mapping to XML).