Kohana request security - model-view-controller

I've searched previous answers but can't seem to find the exact answer.
I am using ajax to call a controller action. This controller action does some other stuff then calls a public function of my user controller:
Request::factory("/user/savepoints/".$new_total);
How can i secure my action_savepoints in the User controller from people just entering it as a URL?
I currently have this at the top of my function but it doesn't do what im looking for.
if( ! $this->request->is_initial() ):
HTTP::redirect('/error');
endif;
Thanks for your help.

Either use an HTTP POST request, which can't be done just by entering a URL. (Though it can spoofed, or done via a form)
Or:
How about generating a kind of token on the server, getting it to the ajax code somehow, then passing it back in the ajax request.
Obviously they could still forge the request manually if they pull the token out of your page, but you issued them the token in the first place.
You could make the token single-use, time limited, or user-specific.
Make sure it contains some kind of checksum with a server secret to prevent people building their own tokens.

Do you want to prevent any unauthorized users to run the script or do you want to make sure that the script only can be run via AJAX calls?
For the first, you can just check if the user is logged in. The AJAX request uses the same session as the ordinary requests.
if (Auth::instance()->logged_in())
For the second you need to check the HTTP headers if it's an AJAX call. But note that this is not a safe way to do it as HTTP headers can be altered by the client and can not be trusteed.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
//This is an ajax call
}
Unfortunately, there's no bullet proof or safe way to detect an AJAX request other than this.

Related

redirection after 'delete' in express

From the client side, I am making an Ajax request of type "delete" using jquery.On the server side, I am doing res.redirect(URL).But instead of redirecting, browser is again making a delete request with URL returned from server side for redirecting.
However, it is not happening for a post request.Everything is OK with post request.
Short version
Ajax is trying to follow the request to it's bitter end to get a successful response (2xx). If you want to delete a resource and send the user to a new web page, you will need to handle that after receiving a success response from your Ajax call.
Full explanation
While redirects are sometimes used after processing a request (such as a successful / failed login) it's not really what they're intended for. Generally you would only redirect the user to get them to the resource their looking for. For example, you might move an endpoint such as POST /blog-post to the new location of POST /blog-article. What you're saying to the requester here is that something used to be where it is, but now they need to make a request elsewhere to find what they're after. This is incredibly important when trying to prevent link rot.
The idea of accepting and processing a request, and then moving the user off to another page is more of a coincidence really. It just happens to work due to how a browser handles URL requests.
I expect your POST request is actually using a form, in this case the browser is following the redirect because it received something like a 301 and is attempting to see a request chain through. However when using Ajax a redirect is being handled by the Ajax call itself, not the entire browser. Ajax in this case is acting as if you'd expect if the endpoint had been moved. So for example, if you moved the endpoint on the server side, your application would still function as it would follow the redirect instruction.
What you really need to do is return a successful response to your Ajax call such as a 204 (No content) and then in your frontend move the user on to a new page.
This isn't as convenient I'll admit, but when you understand why the redirects actually exist it makes more sense. They're not a way of telling a user to move onto something else, they're a way of trying to prevent link rot and enable applications to continue working against an API which may have changed slightly.

Is it safe to set an anti-CSRF token on $http for Ajax requests?

It seems creating and handling anti-CSRF tokens for Ajax calls in an Angular application is non-trivial and some are getting around the problem by applying a single token to every Ajax call. For example here.
The solution is quite neat. We just generate the token on the server and send it along with the first loaded page after sign-in. Then we ensure it goes out with all future requests like this:
$http.defaults.headers.common['RequestVerificationToken'] = 'token should go here';
But I am concerned this may simplify the job of an attacker. They need only get hold of $http in order to make any valid request. Is this the case? Is this method safe? Is there a 'best practice' regarding Ajax requests and CSRF?
Angular automatically does this for you.
Read Cross Site Request Forgery (XSRF) Protection section.
DOCS
I also suggest you read up CSRF, and what it is, if malicious script is already in your page it does not need to do cross-site requests to pose as the victim.

NancyFx. Forms authorization. Ajax and unauthorized response

I use wcf-hosted NancyFx with forms authorization with redirection enabled (DisableRedirect = false).
I would like in case of unsuccesfull authorization attempt handle it and signal to user (show some tooltip that user name or password is wrong). How can I do it with FormAuth?
Another approach is to use Ajax post request, but because of redirection I can't get 401 code. If I turn off redirection it works (I can get 401 in ajax post request). But I want to use redirection facilities in my application...
I never work before with FormAuth, so what is my options here?
Thanks in advance!
Well, actually there were obvious solution based on parsing returned querystring (smth like login?error=true&username=a, as in examples for Nancy forms auth app). On document load parse this query string and show tooltip... Another question whether it is standart (good) practise?..

Considering authentication when using Ajax with Spring MVC

I am trying to use ajax in my spring mvc application. When I try a url (post/get) which is secured and needs authentication, the response is the html of login page as it is redirected behind the scenes.
What is the best approach to overcome this issue?
First, I would avoid displaying Ajax links to URLs needing authentication if the user is not authenticated, if possible.
If not always possible, your login page could be returned with a specific HTTP response code, (or any other way to distinguish it from a normal response) and your JavaScript callback could replace the entire body of the current page with the HTML received if this response code is received. Most AJAX libraries come with a way to define a handler to all the AJAX requests. Such a global handler could be used here.
The login page could also be adapted to only return a status code in case of an AJAX request, and the JavaScript code would then redirect to the login page (without using AJAX) if this status code is received.
I may not have explained the issue well. So I did not get the right response. However the response from JB Nizet contained some other points. So thank you.
I could solve the issue after coming back to this issue after some time, so
I posted about this on my blog.
I hope it is useful.

Different behavior in GET vs. POST Ajax request

We have an MVC app that uses controllers for AJAX endpoints, and FormsAuth for authentication.
I've run into an interesting scenario where a GET request will behave differently than a POST request (both for an unauthorized user).
In this particular case, our custom ControllerFactory runs the following code trying to access this controller:
FormsAuthentication.SignOut();
requestContext.HttpContext.Response.Redirect(FormsAuthentication.LoginUrl);
throw new UnauthorizedAccessException();
(I realize that redirecting inside an AJAX request makes no sense, but bear with me).
When I do a GET request (AJAX) to this controller, the client receives a 401 - Unauthorized exception, which I can trap on the client side and redirect the user to the login page.
When I do a POST request (AJAX) to this controller, I'm getting a 302, and my request got redirected to my login page.
Why do the GET and POST requests act differently?
So I took Darin's advice and did some refactoring, and I no longer run into this problem. :) I discovered the root of my problem, which was that we had a attribute for MVC error handling that did not have the IExceptionFilter attribute, so some stuff was happening in non-determinate orders. Thanks for the helpful kick in the butt. ;)

Resources