How to detect if the user of a Silverlight app is logged into server? - asp.net-mvc

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

Related

Grails Spring Security Last Request URL when AJAX

I'm recently facing the problem with last request url after login. Normally, everything works properly. But if I proceed following procedure I have troubles:
Open an App in one tab and log in
In this tab I go somewhere where AJAX request to the server are proceeded regularly
Open a new tab with the app (I'm still logged-in)
In this tab I log out
In the mean time the AJAX request from the 1st tab is proceeded automatically
with HTTP 401 (cause I've logged-out)
When I try to log in again in the 2nd tab than I receive the JSON of the AJAX request from the 1st tab because it was the last request.
I would suspect that Spring Security would neglect AJAX request for "last request url". Is it possible to set this somewhere? Or is there any good workaround to this?
Thanks,
Mateo
I don't think there is a general way to distinguish ajax requests from "regular" requests initiated by the user navigating a browser. If you can distinguish them in your application (e.g. by mapping ajax requests to specific urls that can be matched against some patterns), you could easily implement what you are looking for. (EDIT: An easier way to identify ajax requests is suggested by Sérgio in his below comment.)
The component that is responsible to perform redirection after a successful login is SavedRequestAwareAuthenticationSuccessHandler, therefore one possibile way to customize the framework's default behavior is to provide your own AuthenticationSuccessHandler, and inject it into the UsernamePasswordAuthenticationFilter. It should be possible to autowire the RequestCache in your class, and decide if you want to replay the last cached request or just ignore it in case it's known to be an ajax request.

Why does HttpAntiForgeryException occur randomly even with a static Machine Key?

We have an ASP.NET MVC 2 (.NET 4) application running on Windows Azure (latest 2.x OS version) with two web role instances.
We use the anti-forgery token supplied by MVC for all POST requests, and we have set a static Machine Key in web.config, so everything works on multiple machines and across restarts. 99.9% of the cases it works perfectly.
Every now and then, however, we log a HttpAntiForgeryException, with message "A required anti-forgery token was not supplied or was invalid."
I know the problem might be cookies not being allowed in the browser, but we've verified that and cookies are enabled and being sent back and forth correctly.
The error occurs with a variety of browsers and obviously causes problems to the users because they have to repeat the operation or they can lose some data. Suffice it to say, we haven't been able to reproduce the problem locally, but it only happens on Windows Azure.
Why is that happening? How can we avoid it?
I ran into this recently as well and found two causes.
1. Browser restores last session on open for page that is cached
If you have a page that is cachable that performs a post to your server (i.e. antiforgery will be on) and the user has their browser set to restore last session on start up (this option exists in chrome) the page will be rendered from cache. However, the request verification cookie will not be there because it is a browser session cookie and is discarded when browser is closed. Since the cookie is gone you get the anti-forgery exception. Solution: Return response headers so that the page is not cached (i.e. Cache-Control:private, no-store).
2. Race condition if opening more than one tab on start up to your site
Browsers have the option to open a set of tabs at start up. If more than one of these hit your site that returns a request verification cookie you can hit a race condition where the request verification cookie is overwritten. This happens because more than one request hits your server from a user that does not have the request verification cookie set. The first request is handled and sets the request verification cookie. Next the second request is handled, but it did not send the cookie (had not been set yet at request time) so the server generates a new one. The new one overwrites the first one and now that page will get an antiforgery request exception when it next performs a post. The MVC framework does not handle this scenario. This bug has been reported to the MVC team at Microsoft.
The anti forgery token contains the username of the currently connected user when it is emitted. And when verifying its validity, the currently connected user is checked against the one used when the token was emitted. So for example if you have a form in which the user is not yet authenticated and you emit an anti forgery token, there won't be any username stored in it. If when you submit the form you authenticate the user, then the token will no longer be valid. Same applies for logging out.
Here's how the Validate method looks like:
public void Validate(HttpContextBase context, string salt)
{
string antiForgeryTokenName = AntiForgeryData.GetAntiForgeryTokenName(null);
string str2 = AntiForgeryData.GetAntiForgeryTokenName(context.Request.ApplicationPath);
HttpCookie cookie = context.Request.Cookies[str2];
if ((cookie == null) || string.IsNullOrEmpty(cookie.Value))
{
throw CreateValidationException();
}
AntiForgeryData data = this.Serializer.Deserialize(cookie.Value);
string str3 = context.Request.Form[antiForgeryTokenName];
if (string.IsNullOrEmpty(str3))
{
throw CreateValidationException();
}
AntiForgeryData data2 = this.Serializer.Deserialize(str3);
if (!string.Equals(data.Value, data2.Value, StringComparison.Ordinal))
{
throw CreateValidationException();
}
string username = AntiForgeryData.GetUsername(context.User);
if (!string.Equals(data2.Username, username, StringComparison.OrdinalIgnoreCase))
{
throw CreateValidationException();
}
if (!string.Equals(salt ?? string.Empty, data2.Salt, StringComparison.Ordinal))
{
throw CreateValidationException();
}
}
One possible way to debug this is to recompile ASP.NET MVC from its source code and log exactly in which of the if cases you enter when the exception is thrown.
I have a few MVC3 web apps that get this pretty regularly also. The majority of them are because the client doesn't send a POST body. And most of these are IE8 because of some bug with ajax requests preceding a regular form post. There's a hotfix for IE that seems to address the symptoms, which sort of proves that it is a client bug in these cases
http://support.microsoft.com/?kbid=831167
There are a few discussions about the issue around the web, nothing too useful though, I definitely am not about to mess with keep-alive timeouts which is a suggested "solution" in some places...
https://www.google.com/search?q=ie8+empty+post+body
I've never been able to reproduce it with a variety of attempts to reset connections between POSTS so I'm afraid I don't have a real solution for the case of the IE empty POST bodies. The way we've mitigated it a little bit is to make sure that we never use the POST method when just retrieving data via ajax.
If you log the full request, check to see if the POST body is empty, and if it is, it'll probably be an older IE. And I don't mean Content-Length: 0, it will usually have a Content-Length that seems correct in the headers but there will literally be nothing after the headers in the request.
The issue as a whole is still a mystery to me though because we still get the occasional exception where there is a complete POST body. Our usernames never change and our keys are static as well, I haven't tried adding debugging to the source, if I ever get around to that I will report my findings.
There are a couple of options for what you could try. You could try remoting into the machine and looking at the event log to see if you can get more information from that in regards to where this is happening. If that doesn't help, you can use DebugDiag or some other tool to capture a dump of the process (DebugDiag will let you capture one at the time of this specific exception). And then look at that to see what is going on.
If you can't seem to figure it out from there, you can always create a support case with Microsoft to help you investigate it.
I have encountered similar problems with my home-brewed anti-forgery code, which is conceptually very similar to the MVC mechanism. Mostly the problem seems to occur because modern browsers appear willing to display cached copies of pages specified as non-cached.
I have tried all combinations of page no-cache directives, but sometimes I still get cached pages displayed.
I have found that a better solution is to hook the onbeforeunload event for the page and explicitly clear the value of the hidden input field holding the token value in the DOM.
If a cached copy of a page is loaded, it seems to contain the cleared input field value. I then test for this in the document ready function and reload the page if necessary:
window.location.reload(true);
Seems to work quite effectively, and I suspect it might for the MVC anti-forgery code too.

In an ASP.NET MVC 3 application, how can I save the post data in the where their session times out

I have an ASP.NET MVC 3 application. The site involves people writing lengthy responses using a textarea in a web form. Occasionally, users are complaining that they are getting redirected to the log in form after they post their data. I am not sure exactly why they are getting logged out because the users do not typically provide enough information on their errors. I believe it is due either to a session time out or the application has been restarted for some reason. This is on a shared web hosting site and it does not have its own app pool.
In any case, regardless of the reason, I would like to capture that post data and save it to a db or text file. How can I get the post data and save it while the controller redirects the user to the login screen.
I know the long term plan would be to identify why the timeout is occurring. But for now I want to be able to grab the post data and recover it at a later time.
First, in order to avoid timeouts, I would recommend using client-side heartbeat solution (like http://plugins.jquery.com/project/Heartbeat)
Second, assuming that you are using forms authentication, in order to save posted data, when Forms Authorization Module is redirecting your users, you will need to intercept redirects in EndRequest HttpApplication event handler in Global.asax or your own module.
The way to intercept those requests is not that straightforward, since on "EndRequest" pipeline step you will see 302 HTTP status code (redirect instruction), not 401 (Unauthorized error). So you may check if request is not authenticated (HttpContext.User.Identity.IsAuthenticated) and request is redirected - in this case you may save what you see in the request.
Otherwise you would need to disable forms authentication and use some solution, which is closer to ASP.NET MVC.
one solution can be to put a javasscript timer which keeps on hitting the server after specified interval to keep session alive until u figure out the cause of session time out (only i its the session timeout problem)
If you want to stop the session from timing out, you can add a hidden iframe on the page. For example, create a new page called KeepSessionAlive and do this:
<meta http-equiv="refresh" content="600">
where content = seconds.
I don't know about MVC 3, but the way you can get and store the post values is to catch them before redirecting the user to the Login page.

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. =)

What's the correct response to unauthorized HTTP request?

I am writing web application I am not sure what is the correct response to unauthorized request. For user it is convenient when server response with 302 and redirects him to login page. However somewhere deep inside I feel that 401 is more correct. I am also little afraid if the 302 cannot be misinterpreted by search engines.
So how do you response to your unauthorized requests?
Edit
I am using ASP.NET MVC. This is not important from theoretical point of view. However ASP.NET form authentication use 302 approach.
I also like the behavior when user is redirected after successful login to the page he was requested. I am not sure if this can be implemented with 401 approach easily.
I think the correct response is entirely dependent on the context of the request. In a web application intended for human (not machine) consumption, I prefer to either redirect to login if the user is not authenticated and render an error page if the user is authenticated, but not authorized. I won't typically return an unauthorized response as it contains too little information for the typical user to help them use the application.
For a web service, I would probably use the unauthorized response. Since it is typically consumed by a program on the other end, there is no need to provide a descriptive error message or redirection. The developer using the service should be able to discern the correct changes to make to their code to use the service properly -- assuming I've done a good job of documenting interface usage with examples.
As for search engines, a properly constructed robots.txt file is probably more useful in restricting it to public pages.
401 seems grammatically correct, however a 401 is actually a statement presented back to the browser to ask for credentials - the browser would then expect to check the WWW-Authenticate header so that it could challenge the user to enter the correct details.
To quote the spec.
The request requires user
authentication. The response MUST
include a WWW-Authenticate header
field (section 14.47) containing a
challenge applicable to the requested
resource. The client MAY repeat the
request with a suitable Authorization
header field (section 14.8). If the
request already included Authorization
credentials, then the 401 response
indicates that authorization has been
refused for those credentials. If the
401 response contains the same
challenge as the prior response, and
the user agent has already attempted
authentication at least once, then the
user SHOULD be presented the entity
that was given in the response, since
that entity might include relevant
diagnostic information. HTTP access
authentication is explained in "HTTP
Authentication: Basic and Digest
Access Authentication" [43].
If you do a 302 you at least guarantee that the user will be directed to a page where they can log in if non-standard log in is being used. I wouldn't care much what search engines and the like think about 401's.
Send a 401 response, and include a login form on the page you return with it. (i.e. don't just include a link to the login page, include the whole form right there.)
I have to agree with you that the 401 result is actually the correct response.
That said why not have a custom 401 page which is well designed and shows the unauthorised message as well as a link to the login page, which you could have a 15 second javascript countdown to automatically send them there.
This way you give the correct 401 response to a bot which is told that the page is restricted but a real user gets redirected after being told that they are accessing a secured resource.
Don't bother about the search engines if your site is mainly used by humans. The ideal approach when a user reaches a protected page is to redirect them to a login page, so that they can be forwarded to the protected page after successful login.
You cannot accomplish that with a 401-error, unless you are planning to include a login form in the error page. From the usability point of view, the first case (302) is more reasonable.
Besides, you could write code to redirect humans to your login page, and search engines to 401.
How are the search engines going to be indexing the secured pages in the first place? Unauthorized users, such as bots, shouldn't be getting that far in the first place IMHO.

Resources