OAuth 2.0, how to properly handle browser back button that navigates to an exchange endpoint? - model-view-controller

I am implementing OAuth 2.0 protocol within my MVC application. Everything seem to working as expected except for one thing.
How do I handle a scenario with a browser back button when user is been redirected to their application after exchange end point has been completed? Problem is that browser caches state and code parameter and obviously code has already been exchanged.
I can always but some guard code to see if exception is thrown to send user back into original sign in flow that will redirect them to the default pages since there will be already SSO session. Not sure if this is a proper solution.
For information I am using Identity Server and mix of react, angular, mvc applications.

After doing more research I discovered that you can use 303 instead of 302 status code, in that case browsers should not not cache the first redirect per specification.
However based on the note in 302 section, most modern browsers implement 302 as if was 303 redirect and not caching the response.
The solution was, I started adding cache control header with no-cache value to my 302 redirects and browser does not take me back to the previous redirects.
Here is the documentation I took this from: https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
I used 302 instead of 303 because I have multiple redirects and documentation states that in 303 first redirect should not be cached meaning all the other it will ignore.

Related

How HTTP redirects(302) works during an ajax call

I was asked to implement a "one session per account" limitation on an old java 7/struts 1 web application.
During development, I'm getting a behavior which I can't really understand.
So if there's an account "Account-A" currently logged in with a session "Session-1234" and then the same account gets logged in but with a different session "Session-4567" then the session "Session-1234" is marked to be invalidated in the next request performed by that session.
During the process of invalidation of the "Session-1234", one of the steps is redirecting(302) the client to the login page.
Now is what I don't understand.
If the request is coming in "synchronous" mode, everything works as expected.
User clicks some link
Server -> invalidates session and redirects(302) login.
Browser -> detects 302 looks for Location header and performs a get.
Server -> serves the resource.
Browser -> show login and update the URL.
If the request is coming in "asynchronous" mode aka AJAX, now I have problems because what happens is that the page never changes and the content of the login is displayed right there.
My question is not how to solve this "problem", but rather have a really good grasp on why it behaves like this.
If you are working with a programmatic client, you have 2 main options:
Don't use cookies, use the Authorization header and let the server emit a 401, telling the client their token is now invalid.
With your javascript client, read if the server returned a 302 response and Location header and respond to that.
#2 is basically a hack that lets you mimic the standard browsers' behavior. #1 is more appropriate for an API.

Do browsers allow cross-domain requests to be "sent"?

I am newbie to website security and currently trying to understand Same-Origin-Policy in some depth.
While there are very good posts on stackoverflow and elsewhere about the concept of SOP, I could not find updated information on whether chrome and other browsers allow cross-domain XHR post requests to be 'sent' from the first place.
From this 5 year old post, it appears that chrome allows the request to pass through to the requested server but does not allow reading the response by the requester.
I tested that on my website trying to change user info on my server from a different domain. Details below:
My domain: "www.mysite.com"
Attacker domain: "www.attacker.mysite.com"
According to Same-Origin-Policy those two are considered different Origins.
User (while logged in to www.mysite.com) opens www.attacker.mysite.com and presses a button that fires a POST request to 'www.mysite.com' server...The submitted hidden form (without tokens in this case) has all the required information to change the user's info on 'www.mysite.com' server --> Result: CSRF successful attack: The user info does indeed change.
Now do the same but with javascript submitting the form through JQuery .post instead of submitting the form--> Result: Besides chrome giving the normal response:
No 'Access-Control-Allow-Origin' header is present on the requested
resource
, I found that no change is done on the server side...It seems that the request does not even pass through from the browser. The user info does not change at all! While that sounds good, I was expecting the opposite.
According to my understanding and the post linked above, for cross-domain requests, only the server response should be blocked by the browser not sending the post request to the server from the first place.
Also, I do not have any CORS configuration set; no Access-Control-Allow-Origin headers are sent. But even if I had that set, that should apply only on 'reading' the server response not actually sending the request...right?
I thought of preflights, where a request is sent to check if it's allowed on the server or not, and thus blocking the request before sending its actual data to change the user info. However, according to Access_Control_CORS , those preflights are only sent in specific situations which do not apply to my simple AJAX post request (which includes a simple form with enctype by default application/x-www-form-urlencoded and no custom headers are sent).
So is it that chrome has changed its security specs to prevent the post request to a cross domain from the first place?
or am I missing something here in my understanding to the same-origin-policy?
Either way, it would be helpful to know if there is a source for updated security measures implemented in different web browsers.
The XMLHttpRequest object behavior has been revisited with time.
The first AJAX request were unconstrained.
When SOP was introduced the XMLHttpRequest was updated to restrict every cross-origin request
If the origin of url is not same origin with the XMLHttpRequest origin the user agent should raise a SECURITY_ERR exception and terminate these steps.
From XMLHttpRequest Level 1, open method
The idea was that an AJAX request that couldn't read the response was useless and probably malicious, so they were forbidden.
So in general a cross-origin AJAX call would never make it to the server.
This API is now called XMLHttpRequest Level 1.
It turned out that SOP was in general too strict, before CORS was developed, Microsoft started to supply (and tried to standardize) a new XMLHttpRequest2 API that would allow only some specific requests, stripped by any cookie and most headers.
The standardization failed and was merged back into the XMLHttpRequest API after the advent of CORS. The behavior of Microsoft API was mostly retained but more complex (read: potentially dangerous) requests were allowed upon specific allowance from the server (through the use of pre-flights).
A POST request with non simple headers or Content-Type is considered complex, so it requires a pre-flight.
Pre-flights are done with the OPTIONS method and doesn't contain any form information, as such no updates on the server are done.
When the pre-flight fails, the user-agent (the browser) terminate the AJAX request, preserving the XMLHttpRequest Level 1 behavior.
So in short: For XMLHttpRequest the SOP was stronger, deny any cross-origin operations despite the goals stated by the SOP principles. This was possible because at the time that didn't break anything.
CORS loosened the policy allowing "non harmful" requests by default and allowing the negotiation of the others.
OK...I got it...It's neither a new policy in chrome nor missing something in SOP...
The session cookies of "www.mysite.com" were set to "HttpOnly" which means, as mentioned here, that they won't be sent along with AJAX requests, and thus the server won't change the user's details in point (4).
Once I added xhrFields: { withCredentials:true } to my post request, I was able to change the user's information in a cross-domain XHR POST call as expected.
Although this proves the already known fact that the browser actually sends the cross-domain post requests to the server and only blocks the server response, it might still be helpful to those trying to deepen their understanding to SOP and/or playing with CORS.

Backbone Collection.fetch() when after session timeout

I have an ASP.NET MVC4 sub web application added in to an existing ASP.NET WebForm web site. the whole website is using forms authentication.
In my MVC4 client side, I use Backbone.js for building the application, and the client application is most likely a SPA.
Everything works fine, but after session timeout my application does not redirect to log-in page.
I tried the error callback on Collection.fetch method, it was triggered (which is good) when trying to fetch after session time out.
However, the response status code is 200 (OK) with response content is the log-in page content.
So, my question is, in error handler how do I know whether the callback is triggered by session timeout or any other unexpected error?
If determined, how should I do to let Backbone redirect page to log-in page while referring current page?
Here is something what Phil Haack had blogged about
Exceprts from the post :
Possible Solutions
I’m going to cover a few possible solutions I’ve seen around the web and then present the one that I prefer. It’s not that these other solutions are wrong, but they are only correct in some cases.
Remove Forms Authentication
If you don’t need FormsAuth, one simple solution is to remove the forms authentication module as this post suggests. This is a great solution if you’re sole purpose is to use ASP.NET to host a Web API service and you don’t need forms authentication. But it’s not a great solution if your app is both a web application and a web service.
Register an HttpModule to convert Redirects to 401
This blog post suggests registering an HTTP Module that converts any 302 request to a 401. There are two problems with this approach. The first is that it breaks the case where the redirect is legitimate and not the result of FormsAuth. The second is that it requires manual configuration of an HttpModule.
Install-Package MembershipService.Mvc
My colleague, Steve Sanderson, has an even better approach with his MembershipService.Mvc and MembershipService.WebForms NuGet packages. These packages expose ASP.NET Membership as a service that you can call from multiple devices.
Some more info from comment of this blog
We had the same problem. But what we did, was to hook to AuthenticateRequest (just like you did) and we also checked the request to see if it's ajax or not (again, just like what you did). But at this point, we simply returned a JSON like {location: 'http://www.domain.com/path-to-login-page'} and we simply ended response in that method with HTTP code 200. This way, jQuery still gets a JSON result. But if the result has a "location" property, we simply do a client-side redirect to login page. That's our way and it works like a charm.

After a POST, should I do a 302 or a 303 redirect?

A common scenario for a web app is to redirect after a POST that modifies the database. Like redirecting to the newly created database object after the user creates it.
It seems like most web apps use 302 redirects, but 303 seems to be the correct thing to do according to the specification if you want the url specified in the redirect to be fetched with GET. Technically, with a 302, the browser is supposed to fetch the specified url with the same method that the original url was fetched with, which would be POST. Most browsers don't do that though.
302 - https://www.rfc-editor.org/rfc/rfc9110.html#name-302-found
303 - https://www.rfc-editor.org/rfc/rfc9110.html#name-303-see-other
So should I be using 302 or 303?
The correct one is 303.
I use it and haven't found any compatibility problems with UAs newer than Netscape 4 (1998, released 17 years ago).
If you use 302, you're risking that UA will re-send POST to the new URL instead of switching to GET.
Still, if you're worried about HTTP/1.0 clients (which don't support vhosts and probably won't be able to access your page anyway) then you should include HTML with link to the new page in body of the 303 response (web servers like Apache do that already).
Depends.
303 and 307 responses were added in HTTP1.1.
So client agents that are strictly compliant to HTTP1.1 RFC should be fine with a 303 response.
But there can be agents that are not fully conformant or are HTTP1.0 compliant and will not be able to handle the 303.
So to be sure that the response of your application can be handled gracefully by the majority of client implementations I think 302 is the safest option.
Excerpt from RFC-2616:
Note: Many pre-HTTP/1.1 user agents
do not understand the 303
status. When interoperability with such clients is a concern, the
302 status code may be used instead, since most user agents react
to a 302 response as described here for 303.
In most server-side languages the default redirection mechanism uses 302:
Java response.sendRedirect(..) uses 302
ASP.NET response.Redirect(..) uses 302
PHP header("Location: ..") uses 302
RoR redirect_to uses 302
etc..
So I'd prefer this, rather than setting status and headers manually.
In theory, you (and all the world) should be using 303 as you have noted. But also, most browsers react to a 302 like they should react to a 303. So, overall, it seems that it won't matter if you send 302 or 303. In the link you provided for the 303 specification, theres an interesting note:
Note: Many pre-HTTP/1.1 user agents do not understand the 303 status. When interoperability with such clients is a concern, the 302 status code may be used instead, since most user agents react to a 302 response as described here for 303.
It's important to note the pre-HTTP/1.1 user agents, so maybe this was important a while ago, but I don't believe it is the case now.
So, all in all, it's up to you (I could bet whatever you want that browsers won't change their behavior against 302 statuses never, for fear of breaking the internet for their users).
When providing the location of a new resource created by a POST request, 201 ("Created") is an appropriate response.
HTTP/1.1: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.2
Atom Publishing Protocol: https://www.rfc-editor.org/rfc/rfc5023#section-5.3
This does mean that a web browser probably won't redirect to the new URL, though; the user has to follow a link to get to the new item (this link can be provided in the body of the response, as well as in the Location header).

HTTP site with JSONP API over HTTPS?

Given all the coverage FireSheep has been getting, I have been trying to work out the best practices for balancing HTTP / HTTPS usage for some sites I manage (e.g. blogging sites, magazine sites with user contributed comments).
To me, its over kill to deliver all pages over HTTPS if the user is logged in. If a page is public (e.g. a blog) there is little point encrypting the public page. All I want to do is prevent session hijacking by sniffing cookies over HTTP channels.
So, one plan is:
Login form is over HTTPS
Issue two cookies: One cookie is 'public' and identifies there user for read only aspects (e.g. 'welcome bob!'). The second cookie is private and 'HTTPS only'. This is the cookie that is verified whenever the user makes a change (e.g. adds a comment, deletes a post).
This means that all 'changing' requests must be issued over HTTPS.
We use a lot of AJAX. Indeed, many comment forms use AJAX to post the content.
Obviously, I cant use AJAX directly to post content to a HTTPS backend from a HTTP frontend.
My question is: Can I use script injection (I think this is commonly called 'JSONP'?) to access the API? So in this case there would be a HTTP public page that sends data to the private backend by injecting a script accessed via HTTPS (so that the private cookie is visible in the request).
Can you have HTTPS content inside a HTTP page? I know you get warnings the other way around, but I figure that HTTPS inside HTTP is not a security breach.
Would that work? It seems to work in chrome and FF, but its IE that would be the party pooper!
Another way is to have an iframe which points to a https page that can make all kinds (GET, POST, PUT etc) of Ajax calls to the server over https (same domain as iframe is on https too). Once the response is back inside the iframe, you can post a message back to the main window using HTML5 postMessage API.
Pseudo code:
<iframe src="https://<hostname>/sslProxy">
sslProxy:
MakeAjaxyCall('GET', 'https://<hostname>/endpoint', function (response) {
top.postMessage(response, domain);
});
This works in all modern browsers except IE <= 7 for which you'll have to either resort to JSONP or cross domain communication using Flash.
The problem with JSONP is that you can only use it for GETs.
Can you have HTTPS content inside a
HTTP page? I know you get warnings the
other way around, but I figure that
HTTPS inside HTTP is not a security
breach.breach.
Including HTTPS content inside a regular HTTP page won't raise any alerts in any browser.
However, I don't think JSONP will help you out of this one. Using GETs to post content and modify data is a very bad idea, and prone to other attacks like CSFR

Resources