Session variable equivalent in OWIN self-host - session-variables

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.

Related

Publish event from service layer composed of web applications using service bus

I have read Why not publish NServiceBus messages from a web application and another similar question about this but I am not clear if this applies to service layer as well. For example, if the service layer is composed of web services or REST services built using WCF or Web API or any other way, should those services publish events or send commands? If those services are hosted in load balanced web servers, the problems outlined in the articles apply to this layer as well. How would the recommendation change or not change?
If I look from the definition of Event vs Command, the messages I am talking about are Events e.g. "a user was created" and so an event should be published. As a matter of fact, the service that created the user doesn't even know what else to do i.e. may be another application is supposed to create a customized portal for it and yet another application is supposed to send a welcome kit to the user. This would be an event and not a command. I guess I am hung up on the definition of a web application and application service when application service itself is composed of one or many web applications.
The definition of Web Application
A web application is an application that is accessed by users over a
network such as the Internet or an intranet.
However, to me, the users can be computers and thus web services are web applications and that is the reason for this question.
EDIT:
Let's consider a concrete example. An ASP.NET website (MVC or Web form - doesn't matter) displays the form to the operator, gets a post with data about user creation (Name, UserName, Password) and invokes a WCF service to create the user. In between website and WCF service we can put ServiceBus and send command to create the user (Request/Response) so that we get all the benefits described in the first article. WCF service is the actual business processing layer i.e. it would create the user. That is where I have the question. After the user is created, it should announce that a user has been created and other systems can react to it and do whatever they are supposed to do. So it fits perfectly the pattern of publish the message. However, the WCF service itself is a web application and thus has most of the traits of the web applications and thus the confusion.
As mentioned in the answer to the SO question you linked to, publishing event has more to do with where the actual processing takes places. Just as a side-note: it is not a matter of Send instead of Publish since that would imply that the two are interchangeable whereas they have rather different intentions. When you want to publish, you want to publish.
The same questions should arise if you find yourself publishing from your web-exposed integration layer: should you be performing the business processing in that code or rather sending it off to another endpoint for processing? Typically you should just send it off to another endpoint. You may even consider how you would perform the relevant action should anyone wish to invoke it. For instance, if you are publishing a UserCreatedEvent message it implies that you created a user. How would a user be created? Would I be forced to use the WCF / Web-Api layer or can I send a CreateUserCommand message on the bus that is processed by some application endpoint? If it is the former then you may need to rethink your design. However, if the latter you should be sending the command from your WCF / Web-Api anyway and the processing endpoint will perform the Publish bit :)
update:
My take on it is that it is more about cohesion / concerns. You would typically interact with your domain, from within your business, via a service bus for commands and events, and a simple query layer for reads. If you need to expose anything to a third-party (or simply via the web) then you use WCF / WS / Web-APi. The point is that you should try to avoid business processing in an integration endpoint (or in a front-end like a website). Business processing is better suited to application servers. There are usually exceptions to the rule but if you are in a position to influence the structure then you are in a better space.
The fact is, whatever code is truly responsible for performing the action should be the same which publishes the event. If you've got a MVC app and in the controller itself you're using Entity Framework to insert the User record, then that is exactly where the Publish should be, right after the SaveChanges call. If however, the controller calls a referenced binary or service which does the actions involved in the "add user" call, then the Publish should be there. My thought is the event should be right alongside the code that does the action whose event you are trying to publish.

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.

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

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.

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.

How to force an IIS hosted WCF or ASMX [webservice] to use session object readonly?

While making my first ajax attempts, I decided also, to go to use IIS hosted WCF now. The strange thing is, that the WCF cannot process several requests parallel for the same user/session, if sessionmode is enabled! If sessionmode is disabled on asp.net, the requests are processed parallel. The broser/client may execute several different requests, where some of them are long running. This blocks all further requets and make my ajax app unusable.
This applies to asmx [webservices] also. I had a big hope, to compile the webservice methods using "IReadOnlySessionState" interface, but this has - in oppsite to webpages - no influence. But I need access [most times readonly] to the asp.net session!
Does someone knows any solution to this problems.
Anyway, thanks a lot!
br--mabra
In .NET 4, you can do this in Application_BeginRequest
if (Context.Request.Path.EndsWith("xxx.svc"))
Context.SetSessionStateBehavior(SessionStateBehavior.ReadOnly);
I found this:
http://blogs.msdn.com/silverlightws/archive/2009/09/30/having-a-pollingduplex-service-and-any-other-wcf-service-in-the-same-website-causes-silverlight-calls-to-be-slow.aspx
Which states,
"All WCF services require read/write session state access if you enable ASP.Net sessions, which causes the replies to be queued sequentially. Ideally user should be able configure the WCF handler to be read only, which would allow polling duplex services to work with sessions. Unfortunately this is unsupported at this point."
...the only thing I can think of is if there's some way to manually force early release of the lock. I'm looking into that now.
You can provide a custom session state provider
See: http://koolsand.blogspot.com/2010/02/why-iis-hosted-wcf-services-does-not.html
whenever a request contains svc in the
path it intimates default session
state provider to use readonly lock
and not read-write lock. So using
readonly lock will allow the next wcf
call to be executed concurrently.