Strategies to secure a WCF service, returning Json data requested by jQuery - wcf

I'm having a hard time getting my head around this, and Google just isn't being helpful.
I'm looking at converting some legacy code to use the following technologies: ASP.NET, WCF, jQuery.
The ASP.NET conversion isn't an issue, nor is accessing the WCF service for data, on the server-side.
However, what I'm having an issue with is potentially being able to secure the service so that I can return JSON-formatted data, requested via jQuery on the client-side, but lock it down to prevent external access.
For this particular implementation, it's not that big of a deal, since the ... quasi-Ajax-like functionality has been in place for quite a while, and there hasn't been abuse.
But, once this project is complete, I'd like to take what I've learned and convert another form, which is often abused, and allow for a slicker display.
If I want to do client-side calls to a Web service, am I stuck making my Web service open to anonymous access?
Short of securing the Web interface down to a specific subset of users (I see no issue with securing the added functionality to logged in users), are there any other strategies on securing a Web service in this scenario? Am I just overlooking something obvious?

Require an authenticated session for both the server-side page and its caller via ajax, with both behind HTTPS.
Another strategy is to use a token that is bound to the session during the last page load to confirm that the session itself has not been high-jacked. This is done when the client loads the page. The server tracks what the next token must be to confirm a valid request.

Related

Session variable equivalent in OWIN self-host

I have a sample web API hosted in an OWIN process (self hosted, not in IIS). I get a JWT token in my controller and I want to be able to retreive it in another part of the application, a class that implements NserviceBus IMutateOutgoingTransportMessages. In my other web application POC (hosted in IIS), I used a simple session variable and it works just fine. But I'd like to know what would be the best way to do it in my new OWIN self hosted environment ? Static property in static class ?
This question is really broad and difficult to answer without detailed knowledge of your specific needs. Here's my interpretation of your issue:
You're already signing each request, perhaps storing the token in the browser sessionStorage (or even localStorage), but this does not suffice
You need to retrieve the token outside of or not in relation to any request cycle (if not, this is probably where you should be looking for answers)
Your application does not need to be stateless
Just one static property for one token in a static class would of course start breaking as soon as more than one request hits the application at the same time. Implementing a class that maintains a list of tokens may be a solution, although I can't tell what key you should use to identify each token. Interface details would vary depending on things like if you need to retrieve the token more than once.
Thread safety issues would apply to all handling and implementation of such a class. Using Immutable Collections and functional programming practices as an inspiration may help.
If lingering tokens poses a problem (and they probably would from a security perspective, if nothing else), you need to figure out how to make sure that tokens do not outstay their welcome, even if the cycle is for some reason not completed.
Seeing how you used Session as a solution in your POC, I'm assuming you want some similar behavior, and that one user should not be allowed to carry two tokens at the same time. You could store the tokens i a database, or even in the local file system, making maintenance and validity a separate issue all together.
There are implementations of cache-like functionality already available for OWIN self-hosted applications, and maybe one of those would serve as a shortcut to implementing everything yourself.
If this token business in fact is the only reason for introducing state in your application, then the best solution IMHO would be to rethink your architecture so that the application can remain stateless.
I'm facing a similar dilemma on a server i'm currently developing for a customer. My problem is that the server must make calls (and retain a live connection) with a legacy, multithreaded DLL, (aka the SDK).
I struggled to get this working on IIS with a regular Web API project. Failed badly since IIS recycles threads when it determines that a thread is going rogue... witch is what the SDK thread looks like in that perspective. Also, the SDK must be able to callback on the caller (client - single page app) and for this I'm using SignalR.
I then tried a multi-part system (single page + web api on IIS + WCF service for the SDK integration). But it is a real nightmare to manage because of the 2 way async communication that must occur between all apps. Again: failure.
So I reverted to a single self hosted OWIN + WebAPI service in a console app (for now). My problem is that some of the calls are lengthy and are processed in a worker thread. I managed to pass the SignalR client id in each ajax calls via headers. I can extract the id when in web api controller. But when the task goes async, I need to get the id (via an Unity injected service) from the class that manages the async task. This is where my problem is similar to yours. In IIS hosted apps, we have HttpContext. It is contextualized on each client calls, and follows any thread changes in the pipeline... But not in self hosted OWIN WCF apps...
I'm looking into Thread Local Storage, CallContext... and other means of keeping track of the original caller info during the lifecycle of the async call. I have read about OWIN pipeline, I can capture the info in a OWIN middleware... but how to safely keep that info for use in injected services? I'm still searching for an answer...
I was wondering if you have found a solution to this rather interesting problem ?
I prefer adding to your thread rather than start another parallel thread / SO question.

securing SPA multi-tenant SaaS application

I need some help with securing a single page multi-tenant saas application.
Questions:
1) What is the best way to implement it? I am trying the build the application using angularjs, spring mvc and REST.
2) Can this be done using Spring Security? Any example with creating login page and securing REST, calls will be helpful?
I have found a sample for implementing spring security with Spring JPA (http://krams915.blogspot.com/2012/01/spring-security-31-implement_3065.html) but it is not for SPA and SaaS.
I understand this a very broad question but i am new to SPA, REST and SaaS so any pointers will be helpful.
Thanks...
I have already participated in two projects with SPA and security aspects. Last of them was GWT + Spring Security. I am sure that you can use successfully Angular and Spring Security together.
Unfortunately there is no built-in config parameter 'we are in SPA mode' in Spring Security AFAIK. So some tweaking / conf from Spring Security side will be necessary. Example:
imagine that during login you call built-in into Spring Security login controller. In a case of successfull authentication by default user will be redirected to index page, where in a case of failure it will be redirected to corresponding error page. It is a normal behavior for standard web applications that will be not so useful for SPA web applications. In a case of SPA you need to detect AJAX call and print JSON with username / roles for successfull cases or send 401 code for failures (then detect 401 in JS and show corresponding error). You can use corresponding extention points from Spring Security to do so: AuthenticationSuccessHandler and AuthenticationFailureHandler.
Some another thing to tweak: by default after session expiration user will be redirected to login page (and SPA app receive login page as a response to the next AJAX call).
Looking into my personal exprience general guide will be like so: after login load list of roles into JS. Use it to show / hide corresponding components on UI side. Apply the same list of restrictions on server side too. To make sure that user do not edit JS in browser (although in a case of minified JS of some medium size app it will very complex task). On the server side you must choose between:
Secure URLs of AJAX calls
Secure some Java methods.
I prefer second one (secure business methods on services). I think it is more convinient because normally we want secure business operations, not some endpoints. As adwantage you will be able expose your business logic via some other protocol, and security will be there already. From other side I can imagine some business requirement to have different permissions for different endpoints / protocols. So it depends more on your actual situation.
Lage size JS applications must be splitted into modules. To decrease direct dependencies it may be better to use events insted of direct calls to cummunicate between modules. There are interesting thoughts of Addy Osmany about how to do security in these coditions. I did not found good link to it, maybe this or this will be helpfull (search "permission").
Feel free to post any questions. Good luck.

WCF Sessions on Windows Azure

Our application architecture is as follows:
1) WCF service acts as a facade layer and sits on top of Service, Business Logic and Data Access layer
2) Every client, be it an MVC/ASP.NET, or any other type of application has a ClientTag that first needs to be authenticated and issued an "access token". This token is then passed by the client with every message into the Facade layer
3) The system will be hosted on Windows Azure
This would have been easy to implement with WCF sessions like so:
1) Client initiates a call to WCF to get the token (Client to WCF Session is established, thus every subsequent communication is part of the same "conversation")
2) WCF authenticates the ClientTag, issues the token, and stores it as a local variable
3) Client stores the token in it's own Session and pass it to WCF with every request
Where it breaks down is the fact that Azure (due to its high-availability/load-balancing nature) doesn't support WCF sessions. So, the questions is how do we implement this.
One solution is to use AppFabric caching to imitate session state in WCF layer. We would store the Access Token there and then validate it against what the client passes in. The problem with this is that there is no concurrency between client and WCF. So, we would have to advance WCF session timeout on every request from the same client but we'd want to avoid updating the cache on every request (it could be hundreds/sec).
Any suggestions? Has anyone implemented anything similar to this on Azure. Any feedback would be greatly appreciated.
P.S. It's not only authentication that would happen on the server, but also custom authorization for each client. (Some client might have access to some functions, and others might not).
Thanks!
I'm in the middle of implementing something directly similar to this, but using OAuth 2.0 as the authentication architecture through ACS.
The model I'm following is shamelessly stolen copied from an MSDN sample here: https://connect.microsoft.com/site1168/Downloads/DownloadDetails.aspx?DownloadID=35417. This assumes the client has a user interface, so the user can present some kind of username and password either directly or through some third-party identity provider.
The advantage of this approach is that the WCF layer doesn't need to use any kind of session state, so there's no tedious mucking about with machine keys or whatnot. You'll still get something that can be mapped to an IPrincipal, however, so if you want you can create a custom RoleProvider and use declarative roles in the usual way.
Note the sample uses old-school ASP.NET, and has a dependency on an opaque (and possibly rather buggy) assembly Microsoft.IdentityModel.Protocols.Oauth. And, unless I'm missing something, I've not seen this released anywhere else (e.g. as part of Windows Identity Foundation) so I suspect it's rather new.
An alternative approach could again be to use ACS, this time to authenticate a SAML token, again following the OAuth 2.0 protocols. Details and sample code is here: http://msdn.microsoft.com/en-us/library/windowsazure/hh127795.aspx. That may be better suited to a system with no UI.

Need to authenticate users through a WCF service that is connected to a database

I'm getting increasingly frustrated with doing the authentication right. Usually I'm using terms that I'm not familiar with so answerers misunderstand my questions. Its not helped bu the fact that this is a case with many implementations.
So now I'm going to try to explain the facts and requirements surrounding my project so that I might get a pointer towards a good solution.
I will have a Database that includes the information I need. Included in this info will be the usernames and salted hash of passwords. This database will be connected to a WCF web service that supplies the data to other front end projects.
One of the front end projects is a asp.net MVC 3 web site that users will use to log in and such. Now the default in such a project is some sort of SQlMembership that is not right in this case as this site is not connected to the database (it might not even be a MSQL database).
Here are implementations that I looked at but couldn't quite figure how to use correctly.
1) Write my own MembershipProvider in the MVC project that would query the WebService for validation. Here I mean that it would just call some methods for all its needs. Not liking it for security issues, client side solution.
2) Validata using a service side MembershipProvider but then I would have to send userName Password with each action and I can't store password for security reasons.
3) Then I discovered something called WCF authenticationService http://msdn.microsoft.com/en-us/library/system.web.applicationservices.authenticationservice.aspx and it seemed to be what I need but I'm having problem understanding how it works. I wan't it to be part of my service but it seems to be a dedicated service. Also its not really explaining how it authenticates (I need to have a custom authentication based on my table, not some default table created for me). Here is a post Should authentication be in a separate service for wcf? with same problem that I'm not sure how got solved.
Can the WCF authentication service be the right tool for me?
Can you answer this for someone who doesn't know asp.net, web or service terminology?
EDIT
Here is one solution that I was hoping for but not sure if exists.
The WCF Service exposes a MembershipProvider, RoleProvider, ProfileProvider that are defined in the service.
In the MVC web.config under membership\providers\add the MembershipProvider is added along with a endpoint towards the service. Same with RoleManager etc.
So when I call MembershipProvider in the MVC project to validate user it automatically calls the service and checks there and when it happens upon a Authorize attribute it as well checks the RoleProvider in the service automatically.
I would however also want to restrict the service calls themselves, even if they are inside a [Authorized] attribute method it might not be so in other clients that reference the web service. Would love if when a call comes from a website the service would automatically have access to the forms.authentication cookie.
I am not clear as to what you want to authenticate exactly, if the user login in, or the user accessing you service. Also, I am not sure how you mean for an answer about WCF Security not to use service terminology nor how you expect to solve this without knowing asp.net. I'll do my best though.
If you are authenticating a user login in, you can implement your own MembershipProvider and have a service request credentials and return the authenticated user.
Once authenticated, you can assign each user a GUID. This GUID is the ID which will travel with each message (encoded in the message header) and validate the user to call the service method.
This doesn't involve transport security, which you should configure if you want your message to be secure over the wire, yet this is a different matter, not involving authentication.
Hope this can somehow help you. I tried to make it the least technical possible and left out anything too complicated. Hope this helps somehow...

Best way to use and secure WCF on the Compact Framework?

I am working on an app that has several clients - Desktop, Mobile Device, Web Portal. We're moving to an SOA kind of architecture and will be using WCF.
The WCF story is great when it comes to using netTcp+transport/message security+Windows authentication (or even UsernameToken and a custom UsernameValidator provider) on the Desktop and Web Portal side.
Where it totally breaks down is on the compact framework side...the subset of WCF it supports is so limiting. I was resigned to simply using basicHttp + Username/Password in the headers all over SSL, but it seems that you cannot add headers when on the compact framework stack (no OperationContextScope) - so that leaves me with including username/password as parameters for EVERY SINGLE operation method in the service.
Please tell me I am wrong and there is a better way.
Your best bet is going to be to expose a WCF end-point that conforms to the WS-Security standards.
You should then be able to use those standards for message based security (most likely using X.509). Here's the MSDN link to get started:
Messaging in the .NET Compact Framework
An alternative solution is to pass a ticket (read: guid).
The client logs in (sends username and password). A randomly generated ticket is generated (guid again), cached on the server, and sent back to the client. This ticket is then passed back and forth instead of the username and password.
Of course, all of that is assuming you don't just want to utilize session state.
But in other words: I've had the same problem you've had. It sucks. This is how I got around it a bit so it was usable.
Anyway, another good reference is the WCF Guidance for Mobile.