Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, June 25, 2015

Implicit CSRF protection of ajax requests

Protecting form against CSRF is easy but what about ajax requests, here something more must be done.
It pretty straight forward to just  add the token to the data every time you make a ajax request, but what if you have a framework on top making the ajax request by it self. With frameworks using JQuery, in my case primefaces, this can be solved quite easy.

Primefaces uses the JQuery.ajax method when making ajax requests for many of its components, for example autocomplete. The easies way to do this would then offcourse be to change the underlaying function. Thanks to the way JQuery is built the core methods is very easy to override.

To override a core method in JQuery you just assign the function a new function... =/ like this.

JQuery.ajax = function(settings) {
...
}

The assign function should take the same arguments as the original function. In this case a key/value pair.

Now you just have to put something in the function to append the CSRF token. In my case:

//IPR Ergogroup AS
jQuery.ajax = function(settings) {
if (!settings.dataType)
settings.dataType = 'html';
if (typeof (settings.data) == typeof ('')) {
settings.data += '$CSRFToken=' + CSRFToken;
} else {
settings.data['CSRFToken'] = CSRFToken;
}
orginalMethod(settings);
}

To be able to invoke the original method after doing my stuff I save it to a variable berofe overiding it.
For further reading I recommend the OWASP top 10 publication. Which describes the top 10 security threats to web applications and how to protect against them.

A simple way of doing pagination with Angular UI

In the last few days I have been developing a tool to work with Google fusion tables. In this I display results for a search query in a table with pagination. I found a lot of different ways to do this but I finally ended up with this.
{{column}}
{{cell}}
The relevant part in this is row in queryResult.rows.slice(((currentPage-1)*10), ((currentPage)*10)) track by $index. 

I using the currentPage variable from the Angular UI pagination component in combination with the javascript array slice method to split the result up in pages. Simple and efficient.

Here is a plunker with an example

The limitation of this being that you have to load the entire result at once. Pagination is entirely on the client side and not in the query.

Further reading

This is the book I'm reading to learn AngularJS. Very good and very well formatted for kindle.