How to serve static (or dynamic?) HTML files with RESTful API? - html

Hi I'm studying about RESTful API and making a website running on local to exercise.
I think RESTful is a quite good way. CRUD operations can be identified by HTTP methods and we can handle them with one url.
But most confusing things to me is that, How can we serve HTML files which are needed to request CRUD operations?
For example, If I'm implementing a forum, I need APIs to CRUD posts in forum like
[GET] /forum - see all posts in forum
[POST] /forum - create a new post
[GET] /forum/:id - see the post of id
[PUT] /forum/:id - modify the post of id
[DELETE] /forum/:id - delete the post of id
Think about how we use a forum, we need at least 3 type of HTML pages.
They are,
1. a page to see all posts in forum.
2. a page to see the specific post.
3. a page to type title and contents to create(or modify) a new post.
First and second type of HTML files can be served easily by GET requests above.
But in case of third type HTML files, I need to use extra parameters with above APIs or make a new API such like /forum/createpost to serve such HTML files.
I think, in the point of view of RESTful, I miss something and need to distinguish serving static (or dynamic) HTMLs and handling CRUD requests.
What is the bestpractices to handle this problem?
I also find some questions about this problem, but I couldn't find a clear answer.

I think you are mixing up two separate parts of the application. One is the REST API that provides the endpoints for CRUD operations. The HTML files that send the API requests are not part of the REST API. They are served by a web application that provides the front-end to the user, and makes calls to the REST API in the backend to fetch the information to display. To put it in another way, the web application making the calls is your Presentation layer. The REST API is your Business logic. Presumably, the REST API interacts with a database to write data to and read data from it. That is your Persistence or Storage layer.

You can use HTTP content type negotiation for that. POST/PUT requests (can) contain a Content-Type header declaring the type of content they're sending, and—more importantly—all requests contain an Accept header declaring the kinds of responses it accepts. If the client is accepting text/html responses, serve an HTML page; if they're accepting, say, application/json responses, serve a "RESTful" JSON response. This way your server can respond to different situations with the appropriate content and the same endpoint can serve as API and as HTML handler.
Alternatively, you can distinguish the request by using an extension: /posts.html serves a plain HTML file, while /posts gets served by a REST endpoint. That can easily be done in the web server configuration.

This might or might not be an anwser to your problem, however since you're working in Node + Express, routing might be a way to go (If I understood your question correctly). Below is an example of server implementation of accepted routes with parameters. Note, you can make parameters optional in some cases if needed.
app.get('/', function (req, res) {
res.send('Index')
})
app.get('/forum', function (req, res) {
res.send('Forum Index')
})
app.get('/forum/:id', function (req, res) {
// To access id you do 'req.params.id'
res.send('Forum Index')
})
app.put('/forum/:id', function (req, res) {
res.send('Modify Forum')
})
app.delete('/forum/:id', function (req, res) {
res.send('Delete Forum')
})
Reference : https://expressjs.com/en/guide/routing.html

Related

MEAN.js $http.get() return index html content instead of json file

I'm doing a web app based on original MEAN.js framework. When I want to request local json test file using $http.get() method in my AngularJS file, it returned my index html content.Is it a routing problem? I didnot change the original mean.js routing code(https://github.com/meanjs/mean), just added a $http.get() method in home.client.controller.js file. Can anyone help me with this? Thanks!
That is most likely happening, because you didn't define an endpoint for that particular GET request in your app.
Everytime you make a request to your server (for example a GET request to /my-request) nodejs/express are configured in MEAN.js so that your server will try to find the endpoint for that request, if it does not find any, that request will be handled by this particular code block (specified in /modules/core/server/routes/core.server.routes.js):
// Define application route
app.route('/*').get(core.renderIndex);
Which will basically render the index view.
I'm not sure if you're using a custom module or not, eitherway, if you want that request to be handled in a different way in MEAN.js, you can specify your endpoint in your custom module routes file (or in core.server.controller.js) like so:
// Define application route
app.route('/my-request').get(core.sendMyJSON);
Be careful, because this route must be placed before the one I mentioned earlier, otherwise your request will still be handled the same way and the index view will be rendered and served again.
Then you will have to create the controller that should be called to handle that request:
exports.sendMyJSON = function (req, res) {
// logic to serve the JSON file
};
This way you should be able to get it done with a few adjustments.
Side note:
I'm not entirely sure but I think if you place your JSON file in the public directory of your app you should be able to directly access it without the need for the extra logic.

Preventing access to JSON data in an Angular app

I got a (Flask) backend powering an API that serves JSON to an Angular app.
I love the fact that my backend (algorithms, database) is totally disconnected from my frontend (design, UI) as it could literally run from two distinct servers. However since the view is entirely generated client side everyone can access the JSON data obviously. Say the application is a simple list of things (the things are stored in a JSON file).
In order to prevent direct access to my database through JSON in the browser console I found these options :
Encrypting the data (weak since the decrypting function will be freely visible in the javascript, but not so easy when dealing with minified files)
Instead of $http.get the whole database then filtering with angular, $http.get many times (as the user is scrolling a list for example) so that it is programmatically harder to crawl
I believe my options are still weak. How could I make it harder for a hacker to crawl the whole database ? Any ideas ?
As I understand this question - the user should be permitted to access all of the data via your UI, but you do not want them to access the API directly. As you have figured out, any data accessed by the client cannot be secured but we can make accessing it a little more of PITA.
One common way of doing this is to check the HTTP referer. When you make a call from the UI the server will be given the page the request is coming from. This is typically used to prevent people creating mashups that use your data without permission. As with all the HTTP request headers, you are relying on the caller to be truthful. This will not protect you from console hacking or someone writing a scraper in some other language. #see CSRF
Another idea is to embed a variable token in the html source that bootstraps your app. You can specify this as an angular constant or a global variable and include it in all of your $http requests. The token itself could be unique for each session or be a encrypted expiration date that only the server can process. However, this method is flawed as well as someone could parse the html source, get the code, and then make a request.
So really, you can make it harder for someone, but it is hardly foolproof.
If users should only be able to access some of the data, you can try something like firebase. It allows you to define rules for who can access what.
Security Considerations When designing web applications, consider
security threats from:
JSON vulnerability XSRF Both server and the client must cooperate in
order to eliminate these threats. Angular comes pre-configured with
strategies that address these issues, but for this to work backend
server cooperation is required.
JSON Vulnerability Protection A JSON vulnerability allows third party
website to turn your JSON resource URL into JSONP request under some
conditions. To counter this your server can prefix all JSON requests
with following string ")]}',\n". Angular will automatically strip the
prefix before processing it as JSON.
For example if your server needs to return:
['one','two'] which is vulnerable to attack, your server can return:
)]}', ['one','two'] Angular will strip the prefix, before processing
the JSON.
Cross Site Request Forgery (XSRF) Protection XSRF is a technique by
which an unauthorized site can gain your user's private data. Angular
provides a mechanism to counter XSRF. When performing XHR requests,
the $http service reads a token from a cookie (by default, XSRF-TOKEN)
and sets it as an HTTP header (X-XSRF-TOKEN). Since only JavaScript
that runs on your domain could read the cookie, your server can be
assured that the XHR came from JavaScript running on your domain. The
header will not be set for cross-domain requests.
To take advantage of this, your server needs to set a token in a
JavaScript readable session cookie called XSRF-TOKEN on the first HTTP
GET request. On subsequent XHR requests the server can verify that the
cookie matches X-XSRF-TOKEN HTTP header, and therefore be sure that
only JavaScript running on your domain could have sent the request.
The token must be unique for each user and must be verifiable by the
server (to prevent the JavaScript from making up its own tokens). We
recommend that the token is a digest of your site's authentication
cookie with a salt for added security.
The name of the headers can be specified using the xsrfHeaderName and
xsrfCookieName properties of either $httpProvider.defaults at
config-time, $http.defaults at run-time, or the per-request config
object.
Please Kindly refer the below link,
https://docs.angularjs.org/api/ng/service/$http
From AngularJS DOCs
JSON Vulnerability Protection
A JSON vulnerability allows third party website to turn your JSON resource URL into JSONP request under some conditions. To counter this your server can prefix all JSON requests with following string ")]}',\n". Angular will automatically strip the prefix before processing it as JSON.
There are other techniques like XSRF protection and Transformations which will further add security to your JSON communications. more on this can be found in AngularJS Docs https://docs.angularjs.org/api/ng/service/$http
You might want to consider using JSON Web Tokens for this. I'm not sure how to implement this in Flask but here is a decent example of how it can be done with a Nodejs backend. This example at least shows how you can implement it in Angularjs.
http://www.kdelemme.com/2014/03/09/authentication-with-angularjs-and-a-node-js-rest-api/
Update: JWT for Flask:
https://github.com/mattupstate/flask-jwt

Where to put forms / alternative views in a RESTful html app?

Let's assume an web application that for each URI presents a nice html view for GET requests and allows to update the underlying resource through POST/PUT/PATCH/WHATEVER.
How do I then expose various forms that actually allow performing such requests from the browser? And broader: assuming I have alternative views (possibly also HTML) for the same resource, where do I put those? Arguably, such forms can be considered alternative views, so having an answer to the broader question would be ideal.
Edit: To clarify, my question is not about pure data APIs serving JSON or whatnot, but about HTML apps such as Stackoverflow. For example you can get the collection of questions under /questions and this particular one at /questions/24696982 which makes sense. To get the form to add a new question, you will have to use /questions/ask, which I'm not sure is alright. And that form POSTs to /questions/ask/submit, which seems just plain wrong. Making a GET request to that URL yields a 404 (if anything it should be a 405). The form should be POSTing to /questions. Still I would like to know whether at least the URI for the form is considered acceptable in a RESTful system.
You have a website like, the one way to build a real RESTFull API is to split the frontend and the API - thats in my opinion the best way (some may disagree) - maybe some other don't think like this but lets say the frontend team got www.domain and your team for the API got api.domain.
GET api.domain/questions - Retrieves a list of tickets
GET api.domain/questions/12 - Retrieves a specific ticket
POST api.domain/questions - Creates a new ticket
PUT api.domain/questions/12 - Updates ticket #12
DELETE api.domain/questions/12 - Deletes ticket #12
PATCH api.domain/questions/12 - Partially updates ticket #12 #I only want to display that this also exists - i don't really use it...
AWESOME EDIT: As you can see also stackoverflow uses this method: api.stackexchange.com
So as you can see you can have these structure - but you also can have a form on www.domain/questions/ask and this form would send the request to api.domain/questions via POST. I want to refer to: https://thenewcircle.com/s/post/1221/designing_a_beautiful_rest_json_api_video its a really nice podcast you should have heard.
EDIT: (another point of view)
Another idea is that you can simply choose which content should come back (Json,XML,HTML) if your client sends you the right Accept-Header.
Example 1:
URL REQUEST ACCEPT HEADER RESPONSE
-----------------------------------------------------------------------------------------
domain/questions GET application/json all questions as json
domain/questions GET text/html the page as html with all questions
domain/questions/ask GET text/html Your html for to add a new question
domain/questions POST application/json Add a new new questions (this would be called from ./ask to add the new questions
domain/questions/ask GET application/json 404 Status-Code because on questions/ask you don't have implemented any resource
Example-2:
URL REQUEST ACCEPT HEADER RESPONSE
-----------------------------------------------------------------------------------------
domain/questions/12 GET application/json Shows the questions with the ID 12 as JSON
domain/questions/12 GET text/html Shows the HTML representation of your page
domain/questions/12/edit GET text/html Your html for to edit a the question
domain/questions/12 PUT application/json Updates the questions with the ID 12 // just to add the PATCH thing.. i don't really use it but if you don't update the whole object you could/should use PATCH instead of PUT :p
domain/questions/12/edit GET application/json 404 Status-Code because on questions/ask you don't have implemented any resource
Yesterday I told you about the first idea (which is - I think for using an api as a team (one for frontend and one team that develops the api - a better way) but as #jackweirdy commented (thanks for that - i then searched a lot and was looking at other podcasts from developer around the world and how they would do that) below it's really all up to you - it's your api and at the end you/your team will decide for one way. Hope this helps you or other that looking for how to build a API on a REST background.
The examples in the EDIT-Section would be (if I got it right) not like here on stackoverflow
This is something I've had trouble with myself, and which I don't think there's a right answer to.
Assuming I have an API exposing /people/:id, I generally reserve an endpoint for /people/new. a GET request to that url with Accept: text/html will return a form for creation, but anything else will throw a 404, since this page only exists for people in a web browser. The form on that page will then post to /people/ as you'd expect.
Similarly, if someone wants to edit an existing person, the form to do that might be served from /people/1/update, again HTML only.
If your API has that structure, then I think reserving keywords such as new or update is perfectly reasonable.
As far as I can understand your question, you want an application that :
displays HTML pages (and eventually other formats ?)
displays form views for creation of new elements or for update of existing ones
accept POST/PUT with url encoded data (sent by submitting above forms) to create of update those elements (and eventually other formats ?)
Ruby on Rails is a framework that is targetted as this kind of requirement. Extract from the guide Rails Routing from the Outside In :
HTTP Verb Path action used for
GET /photos index display a list of all photos
GET /photos/new new return an HTML form for creating a new photo
POST /photos create create a new photo
GET /photos/:id show display a specific photo
GET /photos/:id/edit edit return an HTML form for editing a photo
PUT /photos/:id update update a specific photo
DELETE /photos/:id destroy delete a specific photo
You can have HTML views for the actions index, new, show and edit.
Personally, I would recommend to add the following :
POST /photos/:id update update a specific photo
POST /photos/:id/delete destroy delete a specific photo
so that it would be simpler to update or delete elements via html forms.
All those paths are only Rails convention and are not imposed by REST but it gives a clean example of what can be done.
But it is quite easy to make an application following the same or slightly different conventions using other frameworks. Java + Spring MVC can do that very easily, with HTML views using JSP, Velocity, Thymeleaf or others, and the possibility of using JSON in input or output simply using HTTP headers or suffixes in URL (GET /photos/:id.json) with a little less magic but more control than RoR. And I'm not an expert in other framework like Struts2 (still Java), or Django (Python) but I am pretty sure that it is possible too.
What is important :
choose a language (Ruby, Python, Java, PHP, ASP.NET, ...)
choose a framework compatible with RESTfull urls
ensure you can have views in HTML, or JSON, or enter the format you want by adding a suffix or a HTTP header and eventually the appropriate adapter/converter
You could do it by hand but frameworks limits boiler plate code.
The essence of REst was never about how URLs looks like,but how http verbs and headers are used to transfer datas.
This whole "restfull urls" thing is made up by people who dont understand what Rest is. All the Rest spec says is that URLs must be unique.
Now if you really want "restfull" forms,then form should be a resource with an id, like /form/2929929 .Of course it doesnt make sense to do so,since forms are strictly for web users and REst doesnt care about how data is acquiered, only about how it is transfered.
In short,choose whatever URL you want. Some frameworks use new and update for forms. By the way the /questions/ask/submit is totally valid in a Rest context, because what you submit and a question can be 2 totally difference resources.
You need to understand that there is a difference between a RESTfull application and a REST client.
A RESTfull application has pure restfull urls as you described, such as
GET /persons : gets a list of all the persons in database
POST /persons : adds a new person
GET /person/1 : gets a person with id 1
PUT /person/1 : updates person with id 1
DELETE /person/1 : deletes person with id 1
and so on...
Such an application does not have any forms or UI for submitting data. It only accepts data via HTTP requests. To use such an application you can send and receive data using tools like curl or even your browser, which allow you to make HTTP requests.
Now, clearly such an application is not usable from the user point of view. Hence we need to create client applications which consume these restfull applications. These clients are not restfull at all and have urls like:
GET /person/showall : displays a list of all persons
GET /person/create : shows new person form
POST /person/create : submits the data to the restfull application via ajax or simillar technology.
and so on...
These clients can be another HTML application, an android application, an iOS application, etc.
What you are trying to do here is create a single application which has both restful urls for objects as well as forms/pages for data display and input. This is absolutely fine.
Just make sure that you design proper restfull urls for your objects while you can have any url you find suitable for your forms.
In 100% RESTful Web services resources are identified using descriptive URLs, that is URLs composed only of noun phrases.
Generaly speaking, for creating a new resource, you would use PUT, although some frameworks (such as Zend Framework 2, if I remember well), use POST for this purpose. So, for creating a question you could PUT questions, then providing the question identifier in the body of the request, or PUT questions/{identifier}, thus providing the id in the URL.
Contemporary web/cloud applications have moved to what is known as a single page application architecture.
This architecture has a back end REST API (typically JSON based) which is then consumed by either single page applications or native client apps on mobile phones and tablet. The server is then much easier to implement and scale and provides the needed access regardless if its a web client or a native phone/tablet platform.
The client architecture is known as MV* for Model, View and * is anything else the framework provides such as controller logic and persistence.
In my applications I have used a number of MV* frameworks and libraries in anger and investigated many many more. I've had some success with backbone, and my favorite Ember.js, although there are many frameworks and everyone has their favorite for different reasons and that is a whole topic on its own. I will say that depending on the needs of your application different frameworks will be more or less appropriate. I know what matters to my productivity so I have settled on Ember after doing the rounds.
On the backend you have a similar myriad of choices but choose a platform that is known to be mature and stable ans same goes for your data persistence. There are a number of cloud services that give you a REST/JSON api with no coding or deployment concerns now so you can focus more on the client development and less on the server.
It is important to understand that in single page applications the browser url does not need to have a 1 to 1 correspondance with the backend rest api. In fact it would be detrimental to usability taking such a simple minded approach. Of all the client frameworks Ember gets this right as it has a built-in router, and as a result client state is captured in the URL so the page can survive a refresh and can also be bookmarked. You really can keep your client view independent to the backend api endpoints. I design my client URLs around the menu/structure of my forms. In complex apps the URLs nest as far as I need the app to partition and drill down into the details, yet the api endpoints are flat and may span multiple service providers. A view in my client app often assembles data from multiple endpoints and similarly on Accept/Save it pushes to multiple endpoints. It is also possible to implement local persistence so the web client can be used offline and so that temporary or half filled out forms can survive a page refresh.
Another consideration with such an architecture is SEO. With single page applications one needs to be able to provide prerendered pages to web crawlers. Fortunately there are a number of tools which can auto generate the pages for single page applications so that web crawlers can still index your sites content, tools such as pretender.io and many others can solve this for you.
At the end of all this you have a server with a number of REST endpoints and typically a single index.html, app.js app.css and any other assets such as images and fonts.
Typically you need a toolchain for generating these files from your source code which are then either hosted on your domain or on a CDN. I also configure my app and server for CORS so the web client can be hosted on a different domain to the REST back end which also works well in development.
I recommend the broccoli or ember-cli tool chain for assembling all your web client assets and I have also had good experience with Brunch. I've tried most of the tools out there and those are the only ones that get my vote.
For API design I've been actively providing feedback on the latest drafts of JSON API. There is a lot of good work being done there and you can use that as a good starting point.
Usually in production Web Applications I recommend separating how static content is delivered vs how dynamic content is delivered.
Let us hope you are not constrained by SEO and can actually use the wonder of DOM manipulation (ie Client-Side templating)...
I would highly recommend going down the path of learning how to create a SPA (Single Page Application)
However, back to the topic at hand.
Static content (HTML, CSS, Javascript, images) should be delivered thru a different server than your dynamic content (the REST data in json/xml format).
Your HTML should use JQuery/AngularJS/Backbone -- some type of JavaScript framework to actually "render" your HTML on the client-side using JavaScript.
The JavaScript frameworks will also make the proper RESTful calls to POST or PUT a form (which should be a UI representation of some REST path)
Lets say you have a form for a Profile,
GET /profile/{id} would be called to pre-populate a profile FORM
PUT /profile/{id} would be called to update the profile
** JavaScript will pre-populate the FORM by calling one or more RESTful GET methods.
** JavaScript will take entered data from FORM and POST/PUT it to the RESTful server.
The point you should take away from this is:
Let an advanced JavaScript library handle the sending of RESTful requests and "rendering" of the HTML.
HTML is only a template (static content) and can be hosted on a completely different server that is optimized for the job of delivering "static content" :)
Hope that makes sense.
Cheers!
P.S.
Learn about Cross-origin resource sharing (CORS) if you have not already. You will likely need that knowledge to properly host your static content on a different server/domain than your dynamic content.

RESTful web service url html vs json

To generate urls for accessing data for customers, I follow the specification:
Deliver all JSON data pertaining to customers at the URL: wwww.somesite.com/customers
To create, update or delete, use the www.somesite.com/customers/ url with the appropriate verbs i.e. POST, PUT and DEL respectively
However, I want to provide an html page also (preferably at www.somesite.com/customers) which accesses all the JSON data via AJAX calls.
Should I respond at the same url (www.somesite.com/customers) with HTML or JSON based on the headers in the requests? Or is there a better/standard way to do it?
Using headers is tricky to work with. Imo it's best just to use a predictably different url for the api. Such as:
www.somesite.com/customers.json
api.somesite.com/customers
www.somesite.com/api/customers
www.somesite.com/api/v1/customers
As per REST principles the URL indicates the resource and the response is the representation of the resource.
You can generate different representations (JSON or HTML) for the same resource base on client specified criteria. This can be specified through the Accept header item or the Query string.
It is possible.
You can look inside the request if it's an xhr-Request e.g. in express.js it's located at ``req.xhr`. Depend on if it's true you can deliver HTML or JSON.
app.get('/customers', function(req, res){
if(req.xhr){
res.type('application/json');
res.send({});
}else{
res.type('text/html');
res.send('<html>...</html>');
}
});

Using MVC3's AntiForgeryToken in HTTP GET to avoid Javascript CSRF vulnerability

In regards to this Haacked blog, I'm hesitant to implement the proposed anti-JSON GET hijacking solutions since
The recommended solutions to mitigating JSON hijacking involve non-REST-full JSON POSTs to GET data
The alternate solution (object wrapping) causes problems with 3rd party controls I don't have source-code access to.
I can't find a community-vetted implementation that implements the Alternative Solution (listed below) on how to compose the security token, or securely deliver it within the webpage. I also won't claim to be enough of an expert to roll my own implementation.
Referrer headers can't be relied upon
Background
This blog describes a CSRF issue regarding JSON Hijacking and recommends using JSON POSTs to GET data. Since using a HTTP POST to GET data isn't very REST-full, I'd looking for a more RESTfull solution that enables REST actions per session, or per page.
Another mitigation technique is to wrap JSON data in an object as described here. I'm afraid this may just delay the issue, until another technique is found.
Alternative Implementation
To me, it seems natural to extend the use ASP.NET MVC's AntiForgeryToken with jQuery HTTP GETs for my JSON.
For example if I GET some sensitive data, according to the Haacked link above, the following code is vulnerable:
$.getJSON('[url]', { [parameters] }, function(json) {
// callback function code
});
I agree that it isn't RESTfull to GET data using the recommended POST workaround. My thought is to send a validation token in the URL. That way the CSRF-style attacker won't know the complete URL. Cached, or not cached, they won't be able to get the data.
Below are two examples of how a JSON GET query could be done. I'm not sure what implementation is most effective, but may guess that the first one is safer from errant proxies caching this data, thus making it vulnerable to an attacker.
http://localhost:54607/Home/AdminBalances/ENCODEDTOKEN-TOKEN-HERE
or
http://localhost:54607/Home/AdminBalances?ENCODEDTOKEN-TOKEN-HERE
... which might as well be MVC3's AntiForgeryToken, or a variant (see swt) thereof. This token would be set as an inline value on whatever URL format is chosen above.
Sample questions that prevent me from rolling my own solution
What URL format (above) would you use to validate the JSON GET (slash, questionmark, etc) Will a proxy respond to http://localhost:54607/Home/AdminBalances with http://localhost:54607/Home/AdminBalances?ENCODEDTOKEN-TOKEN-HERE data?
How would you deliver that encoded token to the webpage? Inline, or as a page variable?
How would you compose the token? Built in AntiforgeryToken, or by some other means?
The AntiForgeryToken uses a cookie. Would a backing cookie be used/needed in this case? HTTP Only? What about SSL in conjunction with HTTP Only?
How would you set your cache headers? Anything special for the Google Web Accelerator (for example)
What are the implications of just making the JSON request SSL?
Should the returned JSON array still be wrapped in an object just for safety's sake?
How will this solution interop with Microsoft's proposed templating and databinding features
The questions above are the reasons I'm not forging ahead and doing this myself. Not to mention there likely more questions I haven't thought of, and yet are a risk.
The Asp.net MVC AntiForgeryToken won't work through HTTP GET, because it relies on cookies which rely on HTTP POST (it uses the "Double Submit Cookies" technique described in the OWASP XSRF Prevention Cheat Sheet). You can also additionally protect the cookies sent to the client by setting the as httponly, so they cannot be spoofed via a script.
In this document you can find various techniques that can be used to prevent XSRF. It seems the you described would fall into the Approach 1. But we have a problem on how to retrieve the session on the server when using Ajax HTTP GET request since the cookies are not sent with the request. So you would also have to add a session identifier to you action's URL (aka. cookieless sessions, which are easier to hijack). So in order to perform an attack the attacker would only need to know the correct URL to perform the GET request.
Perhaps a good solution would be to store the session data using some key from the users SSL certificate (for example the certs thumb-print). This way only the owner of the SSL certificate could access his session. This way you don't need to use cookies and you don't need to send session identifiers via query string parameters.
Anyway, you will need to roll out your own XSRF protection if you don't want to use HTTP POST in Asp.net MVC.
I came to this problem and the solution was not so trivial however there is a fantastic blog to get you started this can be used with get and post ajax.
http://johan.driessen.se/posts/Updated-Anti-XSRF-Validation-for-ASP.NET-MVC-4-RC
If you place the following in the global name space all your post/gets can take advantage having an anti forgery token and you don't have to modify your ajax calls. Create an input element in a common page.
<form id="__AjaxAntiForgeryForm" action="#" method="post">#Html.AntiForgeryToken()</form>
The following javascript will read the anti forgery tokken and add it to the request header.
// Wire up the global jQuery ajaxSend event handler.
$(document).ajaxSend(namespace.ajax.globalSendHandler);
// <summary>
// Global handler for all ajax send events.
// </summary>
namespace.ajax.globalSendHandler = function (event, xhr, ajaxOptions) {
// Add the anti forgery token
xhr.setRequestHeader('__RequestVerificationToken', $("#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]").val());
};
I think it is legitimate to use AntiforgeryToken (AFT) within an ajax http GET request provided that it is embedded in a form that already provides the AFT and associated cookie. The ajax handler can then do the validate on the server just how it would in a normal form post.