How to pass CSRF token for Rails post request in paw-app - ruby-on-rails

I am attempting to use the Paw app to test out a REST API build in Rails 4.2.4. I have a create method which expects JSON as input. The request appears to pass the correct information from Paws as structure, but the Rails API is failing with the following error:
422 Unprocessable Entity
Can't verify CSRF token authenticity
When writing the JavaScript front end, the request must have a header appended to the request, of the form:
webix.ajax().headers({'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}).post("geo_wells.json", parms), function(text){webix.message("posted");});
That all works fine for getting the CSRF satisfied consistently, although it's the parms I am trying to use Paws to help sort out. But I can't get that meta token in Paws. No idea how to actually add that to the header of the request. Tried creating a cookie and all response cookies, but that didn't do it either.
Any ideas? I'd like to purchase the tool, but if it can't do this, it's not of that much use to me. I would prefer not to up and disable the CSRF as is so often suggested. I'm hoping for a robust answer that would still extend to testing of the fully CSRF enabled API.

This Paw.app article had the answer.
First, install the RegExMatch extension.
See: https://paw.cloud/extensions/RegExMatch
With the Ruby on Rails getting started set up, the regex required to get the csrf token was below:

Related

Invalid authenticity token when POSTing to a Rails API

I have a web application that gets & stores some data through a Rails API.
When I try to "post" to the Rails API, I get an error ActionController::InvalidAuthenticityToken. I know one option is to simply disable the authenticity token requirement on my Rails controller.
Is it possible to have my web app providing a correct authenticity token when it calls the Rails API? How can I do this?
2 Part answer for you here.
First if you are going to be using Rails as an API I would recommend you use another way of validating that the user making the request is actually the user they say they are such as creating a unique token upon account creation or login that can be returned in the initial response and provided as a HTTP header in subsequent requests. If you are worried about the security of this you could optionally base64 encode the key plus some other value and decode it server side before comparison.
If you still wish to use the CSRF method baked in to Rails you can do so as long as the user is making a request from the webapp using AJAX or whatever. If you have the csrf_meta_tags ERB in the header of your layout file you can get the value and set it in the X-CSRF-Token HTTP header. Using jQuery it may look something like:
$.ajaxPrefilter(function(options, originalOptions, xhr) {
var token = $('meta[name="csrf-token"]').attr('content');
if (token) xhr.setRequestHeader('X-CSRF-Token', token);
});
This would cause it to be added to every ajax request made using jQuery.

Can someone explain this paragraph to me from the Rails Security Guide?

See here: http://guides.rubyonrails.org/security.html
[Rails CSRF protection] will automatically include a security token, calculated from the current session and the server-side secret, in all forms and Ajax requests generated by Rails. You won’t need the secret, if you use CookieStorage as session storage. If the security token doesn’t match what was expected, the session will be reset.
I'm really hoping that someone could explain to my why the server side secret is not needed if I store the entire session in a cookie.
The reason I ask is because I am trying to figure out if there is a way to generate CSRF tokens in a 100% client-side application (ember.js) where I won't have Rails inserting a CSRF token on all forms. I can certainly write to cookies using JavaScript, and I can certainly hash various values.
If there is some way to generate a cookie client-side using JavaScript, without a server-side secret, and being able to verify on the server please let me know!
Did you try googling this?
There is plenty of information on jQuery/ember.js/Rails CSRF out there. jQuery has an $.ajaxPrefilter which you can use to append the CSRF token from your META tags to the request headers (and having said META tags existing on page for a single page app shouldn't be a problem).
This article provides one implemenation that uses this method (the example is in Coffeescript).
$ ->
token = $('meta[name="csrf-token"]').attr('content')
$.ajaxPrefilter (options, originalOptions, xhr) ->
xhr.setRequestHeader('X-CSRF-Token', token)
Here is another implemenation extending the DS.RESTAdapter.
All Rails is doing in a 'normal' application is adding the CSRF token as a hidden input field to your forms. Whether coming this way or as an HTTP request header, it's picked up on by rails just the same.
I think it might be if using CookieSessionStore in Rails, there will be a secret token used to sign cookie. Rails may use that secret token instead to verify

Rails API design without disabling CSRF protection

Back in February 2011, Rails was changed to require the CSRF token for all non-GET requests, even those for an API endpoint. I understand the explanation for why this is an important change for browser requests, but that blog post does not offer any advice for how an API should handle the change.
I am not interested in disabling CSRF protection for certain actions.
How are APIs supposed to deal with this change? Is the expectation that an API client makes a GET request to the API to get a CSRF token, then includes that token in every request during that session?
It appears that the token does not change from one POST to another. Is it safe to assume that the token will not change for the duration of the session?
I don't relish the extra error handling when the session expires, but I suppose it is better than having to GET a token before every POST/PUT/DELETE request.
Old question but security is important enough that I feel it deserves a complete answer. As discussed in this question there are still some risk of CSRF even with APIs. Yes browsers are supposed to guard against this by default, but as you don't have complete control of the browser and plugins the user has installed, it's should still be considered a best practice to protect against CSRF in your API.
The way I've seen it done sometimes is to parse the CSRF meta tag from the HTML page itself. I don't really like this though as it doesn't fit well with the way a lot of single page + API apps work today and I feel the CSRF token should be sent in every request regardless of whether it's HTML, JSON or XML.
So I'd suggest instead passing a CSRF token as a cookie or header value via an after filter for all requests. The API can simply re-submit that back as a header value of X-CSRF-Token which Rails already checks.
This is how I did it with AngularJS:
# In my ApplicationController
after_filter :set_csrf_cookie
def set_csrf_cookie
if protect_against_forgery?
cookies['XSRF-TOKEN'] = form_authenticity_token
end
end
AngularJS automatically looks for a cookie named XSRF-TOKEN but feel free to name it anything you want for your purposes. Then when you submit a POST/PUT/DELETE you should to set the header property X-CSRF-Token which Rails automatically looks for.
Unfortunately, AngualrJS already sends back the XSRF-TOKEN cookie in a header value of X-XSRF-TOKEN. It's easy to override Rails' default behaviour to accomodate this in ApplicationController like this:
protected
def verified_request?
super || form_authenticity_token == request.headers['X-XSRF-TOKEN']
end
For Rails 4.2 there is a built in helper now for validating CSRF that should be used.
protected
def verified_request?
super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN'])
end
I hope that's helpful.
EDIT: In a discussion on this for a Rails pull-request I submitted it came out that passing the CSRF token through the API for login is a particularly bad practice (e.g., someone could create third-party login for your site that uses user credentials instead of tokens). So cavet emptor. It's up to you to decide how concerned you are about that for your application. In this case you could still use the above approach but only send back the CSRF cookie to a browser that already has an authenticated session and not for every request. This will prevent submitting a valid login without using the CSRF meta tag.
Rails works with the 'secure by default' convention. Cross-Site or Cross-Session Request Forgery requires a user to have a browser and another trusted website. This is not relevant for APIs, since they don't run in the browser and don't maintain any session. Therefore, you should disable CSRF for APIs.
Of course, you should protect your API by requiring HTTP Authentication or a custom implemented API token or OAuth solution.

CSRF token problem on requests from outside the browser to a Rails server

I need to make an HTTP POST request from outside the browser, but the Rails back-end is not accepting the authentication (error 401). I know I need to pass a CSRF token in such cases, but it's not working.
When I make the request through a form on a browser, it works as expected, but when I try to simulate an identical request (in terms of headers and cookies) from outside the browser (using curl, for example), the authentication doesn't work.
Two small changes allowed me success without a browser: (1) turning off protect_from_forgery, which validates the CSRF or (2) using GET instead of POST for the request. In both cases, passing the cookie is enough. That means the problem is definitely related to CSRF stuff.
So, my question is: how can I make a CSRF-protected HTTP POST to a Rails server without using a browser?
To clarify, the process is broken in three steps:
Login: returns a cookie to identify the session;
New: a GET request that returns the CSRF token to be used later (uses the cookie);
Create: a POST request that submits the information I want to create (uses both the session cookie and the CSRF token).
The only step which fails is the third one.
Assuming your CSRF token is cookie-based, then the program you use to make your requests needs to track cookies. Check out the --cookie-jar option in curl.

Rails POST doesnt extract any path, query or request parameters

I want to grant users access to my API (hosted on heroku.com) from their sites.
But a strange problem occurs, when i want them to allow to post to the api:
Data sent from an correct form with the correct action-url (e.g. "http://myapp.com/projects/123/tasks/321/todos") - the params get serialized and send via jQuery - i encounter an "ActionController::MethodNotAllowed" with the additional info: "Only get and post requests are allowed", that re-routes to ApplicationController#index with :method => :options.
Rails doesnt extract the params for project_id (123) and task_id (321) from the url, neither are any further request_parameters, path_parameters or query_parameters available.
This behaviour occurs, when I POST from external sites, but doesn't occur, when posting from an html-page on my local machine. My first thought was about wrong encoding, but how to fix that problem.
Edit:
I am using authlogic (not devise :-D) and for the :create action the protect_from_forgery is already skipped.
Any suggestions appreciated
i guess that happens because rails tries to protect your form CSRF attacks.
you can comment out the protect_from_forgery line in your ApplicationController to test it.
but im not sure if thats the right way of dealing with this issue in the production environment.
Okay. I'll try and answer the right question this time (see other comment).
So I've thought about this, and I'm wondering, is this a case of the jQuery call attempting a PUT request? When you use the local form Rails will POST the data, but add the extra _method field to emulate a PUT.
Don't know if you are using jquery-rails, but this takes care of setting the _method parameter, and the PUT/POST verb translation for you in your AJAX calls.
The problem occured due to the cross domain policy - the request was made from another domain - and because I was using a recent browser that supports CORS, it was sending an OPTIONS-request first to get known from the server, which actions are allowed for this domain.

Resources