Durandal: intercept view loading to handle unauthorized requests (ASP.NET MVC server) - asp.net-mvc

I've just started converting a Knockout-driven SPA to use Durandal. Due to server legacy, views are served through ASP.Net MVC endpoints that return an ActionResult. In the case of accessing a route that should not be available to the current user, or for example when the session has expired, the server will return JSON instead of HTML.
Durandal seems to make the assumption that HTML will always be returned from the specified view endpoint. Is there any way for me to hook into the process of loading a view so I can process the JSON that comes with an unauthorized request?
In the future the server will be updated to use the Web API. At that point, I will have to solve the same problem, but in that case I will have to handle different response codes.
Thanks in advance!

Here is what I think you may do,
Instead of letting the default view locator load the view for you, you can add a callback method getView method in your viewModel. In the callback method you can load the view (using text.js or jquery), then you have full control of what you want to do with the non-HTML responses (may be switch to a canned error view etc).
More info at Durandal Docs http://durandaljs.com/documentation/Interacting-with-the-DOM/

Related

Asp.net MVC Pass onetime authentication to controller through Url.Action()

Background
I have an ASP.net MVC 4 web application with Forms authentication and a custom AuthorizeAttribute controlling access to all controllers minus the login screen. I am adding to some of the controllers, an action that allows the user to download a server generated PDF whose content and layout is being defined in a Razor View.
To carry out the conversion between Html and PDF, im using a trial version of ABCPdf9 and the bulk of the conversion works perfectly with all CSS, Text, static images, etc being displayed as required.
The problem is that I have images in the HTML that must also be rendered into the PDF file, but these images come from a controller which requires authentication.
Since the Html to PDF conversion takes place in ABCPdf using the Gecko engine, the existing user authentication cookies, etc are not available and as such the GET requests to the Image Controller are not authenticated and will not return anything. (This is the problem).
What I've discovered
From the research I have done, I came across the HttpAdditionalHeaders Property of ABCPdf which (from my understanding) is there to allow you to set header cookies, etc that will be sent with the requests made by the Gecko engine when fetching resources.
I have spent a good few hours trying to set the existing cookies from the originating request and pass them through to ABCPdf but this does not appear to work. Nor does creating a new set of authenticated cookies and pass them either.
So from what I gather, this solution is not possible....
My question
Does anyone know if it is possible to modify the Url.Action helper so it will generate and include a one-time authentication key in the url? Then implement some code in my custom AuthorizeAttribute that strip the key parameter and if valid, provide an alternative method of authentication to access the necessary image controller. This way, I can run the ABCPdf conversion process and it will be able to access the normally restricted resources in the image controller.
For example:
<img src="http://somesite.com/Image/Retrieve/1234?key=WFD6312DFV154WHSF3B1SGB69SB" />
The custom AuthorizeAttribute code should then recognise the key parameter passed in the requests query string and then bypass existing authentication processes.
Any help or even suggestions for where to look would be greatly appreciated!

ruby rails web request response lifecycle

I'm a novice in ruby on rails trying to understand the in-depth flow of a typical request/response life cycle in ruby on rails web application.
I have googled for the info and have not found an answer which is complete or detailed to the level of DNS servers to dispatchers.
The closest I got to a good explanation is at:
http://brainspl.at/request_response.pdf.
Can someone point me to a better or more detailed explanation?
-Raviteja
So you are asking for rails request/response cycle and you already referred to a presentation which really describes it very well. So im assuming that you want to know it from a very high level and you need this concept totally for development. Then here it is. Im just trying to name the parts sequentially.
Route: Here you will draw the paths which will be used by the world to access your application. With a complete RESTful architecture, you need to define the hierarchy of your resources and define how a resource can be accessed to perform some action. If any request to your application doesnt match with any path in the routes file, it will not be processed. If any match occurs, it will find the corresponding controller and action and will call it. At the time of calling, it will store all the request related data in params hash.
Before Filters: Now your application already know which controller#method is gonna process the request. And it will check if there is anything configured to execute before calling that method. This is done by using before_filter. If found anything then those functions will be called first.
Method Execution: After executing all the before_filter methods in a particular sequence, it will call the actual method. All the data is available in params hash in this method. It processes input data, invokes Model calls for database access, and prepare data for view.
View: Proper view file will be chosen based on the controller#action, format. Or you might select any particular view to render by render :partial call. And the response will be prepared using the variables prepared in controller. This response will go to the client.
After Filters: After processing the view, it will look after_filter methods and will those if found.
Well this was a quick overview i would say, without really any details. Im saying again, the pdf you referred really contains more details.
Let me know if you want to know anything more specifically.
A user opens his browser, types in a URL, and presses Enter. When a user presses Enter, the browser makes a request for that URL.
The request hits the Rails router (config/routes.rb).
The router maps the URL to the correct controller and action to handle the request.
The action receives the request, and asks the model to fetch data from the database.
The model returns a list of data to the controller action.
The controller action passes the data on to the view.
The view renders the page as HTML.
The controller sends the HTML back to the browser. The page loads and the user sees it.
https://www.codecademy.com/articles/request-response-cycle-dynamic
and https://www.codecademy.com/articles/request-response-cycle-forms
Everything starts when ‘url’ requested by a user. The browser needs to know sever’s IP address to connect, So it lookup DNS(Domain name system) which translate your domain into the public IP address of the particular server. Then the Browser will do threeway handshake to connect server like puma in port 80. And decide upon public and private key it happen only because if url use HTTPS. HTTPS is a secure wrapper around HTTP and TCP. Then Server triggers the rails application through middleware like rack and provides request verb, header, body to the application. Then rails application use Journey (Default route library of rails) to find the consent controller and action which matches the request and call with the request and params.
Then rails lifecycle callbacks like before, after, around will be triggered during the process. The action takes care of requesting data from the model and rendering the consent view for the request. Finally sent back the status, header, and body as the response.
If you want to learn in-depth about lifecycle, check this article The Lifecycle of a Request
It is also important to note that Rails apps use an MVC architectural pattern, which is Model, View, and Controller at a high-level the life-cycle of a request in rails app is simply the interaction of the Model, View, and Controller. This article gives you an overview.

asp.net mvc 2 -- losing authorization when RedirectToAction with JSON data

I'm refactoring some MVC code that originally used POST'ed form data. The form's fields are serialized using jquery's serialize() method and sent to an MVC controller Save Action that checks things out and redirects as appropriate (if errors in form values, redirect to the Edit Action, if fine then save and redirect to the Display Action). All actions are invoked via AJAX and return Partial Views. Everything works grand. Note: The site uses AD-based authorization, so users are prompted for their windows credentials upon first loading the site, but are never prompted again.
However, I'm now looking to interact with the server via JSON objects instead of form fields. Granted, I serialize the JSON object on the client and, with the aid of an imported MVC2 Futures/MVC3 class JsonValueProviderFactory, am able to correctly model bind the sent JSON object to a C# class in the Controller's parameters.
I maintain the same logic, but things start to blow up when I try to return a RedirectToAction ActionResult when the Controller accepts JSON objects. I lose authentication, the user is prompted for their credentials again, and I find myself in a infinite loop on the originally requested Action (save). Every time the user is prompted for credentials and simply runs through the Save Action again. The end result for the user is an unending alerts prompting for login credentials. Neither of the actions specified in the RedirectToAction calls are ever hit.
Can the fact that the original request uses a JSON contentType be interfering with the behavior of RedirectToAction? That's the only thing I can think of as it works fine when I don't use JSON to post and it works fine when I return PartialViews instead of using RedirectToAction. The infinite repeat of the Controller Action and continual loss of authorization credentials seems to suggest that RedirectToAction is not the way to go in this situation.
I can post code on request. I am also successfully handling stuff like copying the ModelState over to TempData and other RedirectToAction tricks. Again, it DOES work when using a non-JSON solution. Any insight is greatly appreciated!!
EDIT WITH FOLLOW-UP INFO:
Turns out, I get an "Unauthorized" error even when I completely disable NTLM authentication/authorization for the site. IIS server doesn't look for any authorization, web site doesn't look for any authorization, yet the error when trying to Redirect with JSON contentType request still occurs and complains of being "Unauthorized". This is WEIRD.
To update everyone, I haven't found a solution nor do I know for-sure what the situation is. However, I'm willing to bet it has to do with the fact that RedirectToAction issues http GET requests and the action I'm redirecting to only accepts POSTs. Even if I remove the restriction, it's still sending JSON data and it still needs to be done by POST.
In short, RedirectToAction with JSON data appears to be fundamentally undoable. You need to POST JSON data but RedirectToAction emits GET requests. That's my going theory, at least. =)

How to detect if the user of a Silverlight app is logged into server?

I'm looking for a good clean solution to detecting whether a user has been logged out of an ASP.NET MVC application from Silverlight when performing a web request.
The problem is that the website has a Silverlight component that the user could potentially spend a large part of his time in, thus letting him get logged out of the website. Some of the actions in the Silverlight component triggers a web request to the server (using WebClient), generally getting a JSON result. But if the user has been logged out, the result I get is the HTML for the login page of the system (As the request is redirected).
I could check if the response is a valid JSON result, but if I need to introduce other response types later this will fail. I can also begin parsing the response stream to see if it contains elements from the login page but this seems very inelegant and fragile. Perhaps configure MVC somehow to respond to requests from a specific source by returning a know error response.
EDIT
Using Fiddler I found out that I could look for the 302 response code of the HTTP request. However, it turns out that you can't derive from the WebClient class in Silverlight, so I couldn't easily get to the status code. I considered using the WebRequest class instead but it seems a bit too low level for what I want to do. My current solution is to parse the first line of the response stream.
If you are using forms authentication with cookies, you could try to check to see if the cookie is present.
The following link shows how to access cookies in SL:
http://msdn.microsoft.com/en-us/library/dd920298(VS.95).aspx

ASP.NET MVC and Ajax, concurrent requests?

AJAX newbie here!
At the moment in my ASP.NET MVC web app my AJAX requests appear to be getting batched or queued, im not sure.
No requests seem to be getting completed until the previous request has finished.
How do I go about getting the requests to return independantly?
I dont necessarily want someone to give me the answer but maybe some links to good tutorials or resources which could help. Thanks
I'm expanding on Lachlan Roche's answer, which is correct.
The ASP.NET framework will "single-thread" requests that deal with Session scope (a global resource), to prevent one request from interfering with another. In WebForms I think you can use the Page directive to specify that individual pages don't use Session and therefore don't need to treated synchronously like this.
The problem is that in ASP.NET MVC all requests use Session, because it's used to implement TempData. You can disable session state entirely, as Lachlan Roche pointed out, or you can deal with this on a case-by-case basis.
A possible solution might be to kick off your own background threads to process any long-running code, so that the initial request "completes" as quickly as possible.
ASP.NET will serially process requests on a per-session basis unless sessions are configured as disabled or read only in web.config via the enableSessionState attribute on the pages element.
As this is a page setting, this will not affect MVC controllers and they will still be subject to serial request processing.
Curiously, even with sessions disabled or set to readonly, we can still read and write session data. It seems to only affect the session locking that causes serial request processing.
<system.web>
<pages enableSessionState="ReadOnly"/>
</system.web>
Pages can also have an enableSessionState property, though this is not relevant to MVC views.
<%# Page EnableSessionState="True" %>
With the release of ASP.MVC 3 you can now add an attribute to your controllers to mark the Session as readonly, which allows actions to be called concurrently from the same client.
Sessionless Controller Support:
Sessionless Controller is another great new feature in ASP.NET MVC 3. With Sessionless Controller you can easily control your session behavior for controllers. For example, you can make your HomeController's Session as Disabled or ReadOnly, allowing concurrent request execution for single user. For details see Concurrent Requests In ASP.NET MVC and HowTo: Sessionless Controller in MVC3 – what & and why?.
- from this DZone article.
By adding SessionState(SessionStateBehaviour.Disabled) to your controller, the runtime will allow you to invoke multiple actions concurrently from the same browser session.
Unfortunately I don't think there is a way to mark an action so as to only disable the session when that action is called, so if you have a controller that has some actions that require the session and others that do not, you will need to move the ones that do not into a separate controller.
In later versions of ASP MVC you can decorate individual controller classes with the SessionStateAttribute
[System.Web.Mvc.SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
public class MyController : Controller
{
}
Since .NET Framework v3.0 released, you can use "SessionStateBehavior" enum with SessionStateAttribute:
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
public class MyController : BaseController { }
Well Concurrent Request are more on browser dependent aswell if you fire suppose 10 concurrent request to an action Using AJax in Mozilla and same using IE 8 then you will find that Mozilla has style to fire one request wait for its response and then fire second and so on... for this is one by one basis whereas in IE * this fire about 6 concurrent request at a time to Server.
So Concurrent Request are also dependent on browser type.
I suggest using jQuery for your ajax needs with asp.net mvc, I have used it exclusively and it has been extremely easy.
As for tutorials I would look at this: http://docs.jquery.com/Ajax
There are tons of options to play with and I also suggest downloading firebug so you can watch requests launch from your page asynchronously and see if they fire and what they return etc.
Like the other guy side, AJAX request are asynchronous and don't get queued up and they all return independently when they finish, so if you watch in firebug it will be easy to see what is going on behind the scenes and before the debugger gets hit

Resources