WCF service singleton with callback and hosted on IIS? - asp.net

I have a WCF service hosted at IIS7 web application. It's created by a WebServiceHostFactory. The client connects to a service calls the Collect method, and data are stored to DB. All working fine.
Now I would like to refresh page every time the new data are "collected" (i.e. the service method Collect is called).
My question is: What is the best approach ?
I was considering the CallbackContract, but this would require a singleton pattern (service is now PerCall), or is it a wrong assumption ? Is this approach possible ?
My logic is:
ASP.NET page subscribes to WCF service
the service singleton is created from now on
when method is called the services calls subscribers (clients)
there should be therefore only one service instance in order to subscription to work (or is it ?)
the client page refreshes itself
regards,
Kate

You can't refresh the page in a user's browser from the sever. Browsers use HTTP, which is a request-response protocol, so if the browser hasn't issued a request, it won't be looking for a response from your server.
If you have a Silverlight application hosted in a browser, that's a different story, but you didn't mention Silverlight anywhere. You would also be able to do what you're asking using WebSockets in HTML5, but that's not fully standardized yet.

Related

SignalR in WCF service to update web site clients

Using SignalR, is it possible to update website clients from my WCF service if the service is not used by these clients directly?
I have a desktop application in .NET which has WCF service used internally using net.TCP protocol. This application changes one of the status fields in database table depending on certain user actions. I want to notify this change to end users who are accessing a different website hosted on the same web server.
I have tried one SignalR sample where notification works fine if it is sent from same website's host to its own client (stock ticker sample). But in my case, the message should go from WCF service to a website client.
IMO you should do an intermediate hop, for example having your website exposing an endpoint (you pick the technology) where you can post whenever you have a change to notify. Your WCF service would post there whenever there's a change, and the web app would process the post by broadcasting info to the target clients (can be all, or can be just some you filter with some logic behind the post). I use this pattern quite frequently, implementing it with HTTP POST. You would have no issues to implement the SignalR infrastructure in the web app, which is where your clients already connect to.

What are the possible threats while calling web services by using JQuery and how can avoid them?

I know this question can be too generic but for purposes of narrowing the question, here is a brief description:
I'm planning to forget about ASP.net UpdatePanel and move to use ajax via JQuery. I am afraid that because of the plain, client-side nature of JavaScript (and consequently JQuery code), any one looking to my web page's source can realize what is the URL of the web services I'm calling and also what are being passed to those web services.
When using UpdatePanel for these types of operations, I'm sure that calling web services is done on server-side and I have no concern regarding issues of information on calling sensitive web services being exposed publicly but now that I'm planning to use Ajax via JQuery, It worries me alot.
Are my concerns reasonable and if true, what are the best solutions for avoiding the threats of web-service-calling-info being exposed?
Clarification: when saying UpdatePanel, I mean utilizing a chain of techiques including ASP.net AJAX, code-behind and relying on server-side Dlls for performing async server-side operations instead of jquery Ajax which requires web services for intracting with server.
There is no way on the internet to protect your web services all the time by just hiding the URL. I am not sure when you say your updatepanel does the web service call from the server you are not taking the true power of AJAX.
One way to secure your web service is to use the authentication in the web service side. For example you need to send some authentication key every time you access the source, and this is very common, you have so many public web service who protects it self using auth key like OpenId implementation. In case you do not want to change the web service logic I think jquery way of AJAX is not a secure option.
Here's a thought, you can have two levels of web service, one which will open for all that you can use in the jquery. From the current web service, from the server side call the other secure web service. Even now you can configure your incoming request for some specific machine IP.
In this case other than your own server no body else can access to the web service securely kept behind the firewall. It is something similar we do while connecting to database server from application server.
Let me know if this helps.
I'm going to state the problems my answer is hoping to solve:
Assuming you host your services on a machine other than the web server, the problem is you give potential attackers the name/address of those machines.
Attackers can write scripts/bots to scrape your data.
Attackers can focus on your web services and try to hack them/gain access to your network.
Attackers can try to perform a DoS/DDoS on your web services.
The solution I've used in the past is to create a light weight proxy on the web server such that all AJAX calls simply point back to the current domain. Then when a call comes in, it is simply routed to the appropriate web service, which is hosted somewhere internally on the network.
It creates one additional hop on the network, but it also has these benefits:
It hides the actual IP of the machine hosting your services.
You can easily lock down that one web server and monitor unusual activity. If you see a spike in activity, you can potentially shut down the web services. (If you use a different machine, you'd have to monitor two boxes. Not a huge problem, but easier to monitor just one.)
You can easily put a distributed caching layer in the proxy. This protects you from load/denial of service (DoS) attacks and obviously supports normal web service traffic.
You can hide the authentication at the proxy level. The public calls won't betray your authentication scheme. Otherwise an attacker can see what tokens or keys or secrets or whatever that you use. Making a proxy on the web server hides that information. The data will still flow through, but again you can monitor it.
The real benefit in my opinion is that it reduces the surface area of your application which narrows what an attacker can do.
Since you refer to ASP.Net, know its viewstate can easily be decrypted. There's no failproof ways to protect your code (not to say urls called).
If you're web services are called with some parameters that could allow unrestricted and dangerous actions, then you'd better start using some users/roles/rights management.
If you're worried about "man in the middle" attacks, you best option is to use https.

Are webservices exposed to any one?

I'm very new to web services (please note, not WCF but the old fashioned .asmx files).
Now I may be liking this too much to ports, but if I expose a port on my web facing server then it is exposed to attacks as well as my own use; There are tools which can scan to see what ports are open.
Is this true of a web service? Now, don't get me wrong, I know each service should be coded well enough that nothing malicious can happen or that the calling class doesn't know the 'contract' to implement them, but that's not the question (and I guess port flooding could still occur?); If I put up a few web services on a server, is there a tool/program which can detect them (by name)?
Yes, a web service is basically a web page that takes arguments and response with a formatted result that can be read more easily by a program (technically both are a result of a http request and response - there are other mechanisms as well, but the typical one is over the http protocol).
If you type the link to your web service in a browser you will see you are presented with an interface that allows you to "execute" its services.
Therefor you need the same security as with a web page, meaning login or check of credentials, tokens, signing, encryption and so forth (preferably on a ssl-connection).

What is left of an ASP.NET MVC application when consuming an ASP.NET Web API?

As a learning exercise i want to create a simple web api and consume it using a web client(asp.net mvc) and a desktop client(winform).
The web api must handle categories, products and of course users/roles as follows:
everybody can browse categories and products
regular users can insert/update/remove products
administrators can insert/update/remove categories and products
Regarding first consumer, the asp.net mvc application, i have the following questions:
In controllers, will be anything else than ViewResults, because from what i understood all http requests are made from javascript?
What about authentication and authorization?Since we are talking about a RESTFUL service, there is no connection between calls and the user must send in every request some piece of data to identify himself.
2.1 Is there any point in using HTTPVerbs ( in ASP.NET MVC apllication) ?
2.2 What about FormsAuthentication?
2.3 How do i safely send the credentials to the web.api?
Everything is so blurry for me, is there any example with some web api, hosted in the iis independently and consumed by an website (ASP.NET WebForms or ASP.NET MVC) because all examples i have seen weren't that clear.
1) In controllers, will be anything else than ViewResults, because from
what i understood all HTTP requests are made from JavaScript?
Not necessarily. You could perfectly fine use the HttpClient (the Web API Client classes) to consume your RESTful actions directly from your standard ASP.NET MVC actions. For example you could perfectly fine have a repository which uses the HttpClient to consume an ASP.NET MVC Web API method to fetch the data instead of querying a relational database. You should not necessarily expose your WEB API methods to client side JavaScript. They could serve as a gateway to your data access. There are many possible scenarios of course.
2) What about authentication?Since we are talking about a RESTFUL
service, there is no connection between calls and the user must send
in every request some piece of data to identify himself.
There are many ways to perform authentication. One of them is to use Forms Authentication which is a well established mechanism involving cookies. So the piece of data that will be sent from the client to identify himself is actually a cookie in this case.
2.1) Is there any point in using HTTPVerbs?
Of course. REST is all about HTTP verbs. In the case of ASP.NET Web API it is the HTTP verb that determines which API controller action to invoke by convention. You could of course violate this convention by overriding the default routes setup.
2.2) What about FormsAuthentication?
See point 2)

ASP.NET web service using forms authentication from a windows app

I have an ASP.NET web service that I can access via a windows program but now I want to secure the web service. I can secure the web service using forms authentication. How do you access the secured web service from a windows forms application?
Although this is not the right approach, tt is theoretically possible to use forms authentication in the manner you describe. This could be accomplished by either:
Using a WebRequest to send your requests in raw form to the web service. This will involve inspecting the response, extracting the relevant forms-authentication fields, and sending a response back which logs the user in. This will generate a cookie which you must send along with each subsequent response to the service
Generate the FormsAuhentication authentication cookie yourself. This is complex as it involves synchronising the machine key on the calling application, and artificially manipulating the headers being sent to the machine hosting the service.
Display the forms-authentication form for the user to log in to at the beginning of a session requiring interaction with the web-service. You can then harvest the generated cookie and present it to the service in HTTP headers as in option (2).
As you can see, these methods are highly complex, and are fundamentally a hack to use forms-authentication where it was never intended.
Microsoft intended us to use either Windows authentication, or SSL certs to secure access to ASP.NET web services. See HTTP Security and ASP.NET Web Services on MSDN.
If you are able to use WCF, then a few more options present themselves, including the ability to build a custom authentication mechanism into the SOAP, with some support from WCF.
For the most part, securing web services is one of the trickiest parts of the job. Many live solutions which I have seen are compromises such as the ones above.
It seems the answer is no. Forms authentication is a cookie-based mechanism, and your WinForms app won't be able to hold and relay the cookies (without some serious workarounds, if at all).
A potential workaround that I wrote up when researching your question attempted to use a NetworkCredential object, but that didn't work. Also tried was the ClientCredentials in .NET 4.0.
var ss = new MySecureWebService.MyServiceSoapClient();
ss.ClientCredentials.UserName.UserName = "abc";
ss.ClientCredentials.UserName.Password = "123";
string asmxReturn = ss.HelloWorld(); //exception returned here
The console app was still presented with the login html page when calling the webmethod.
Other Suggestions
If you have the source to your web service, extract its logic out into an assembly of its own. Reference that assembly in your WinForms app, and it's just as if you're calling the web service.
I understand that your goal is to reuse the app that's deployed, but the next best thing would be to use the same logic/implementation via .dll reference.
This might help: http://dotnetslackers.com/articles/aspnet/Securing-ASP-Net-Web-Services-with-Forms-Authentication.aspx.

Resources