hanami / controller

Complete, fast and testable actions for Rack and Hanami

Home Page:http://hanamirb.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support CSRF by HTTP header

masterT opened this issue · comments

It would be nice to be able to configure the CSRF validation so it can be read from a particular HTTP header.

Let me know if this is something that would fit into the project, I would be happy to contribute. 🙂

@masterT What's the use case?

I want to protect a web API consumed by AJAX requests by a browser-based client application. I'm using Axios to perform the HTTP requests to the API.

At the moment I'm using a request interceptor to set the CSRF token in the query parameter because it is too hard to set the token in the body (as the body can be String, FormData, Object, Buffer, etc.). This does not feel like the right approach for AJAX requests.

I would like to use the solution proposed by OWASP to set the CSRF token in a custom HTTP header.

For what it's worth, I've also needed to support passing the CSRF token via a header in the past, which I did by patching Hanami::Actions::CSRFProtection to add a method similar to:

def request_csrf_token(req)
  req.params[CSRF_TOKEN] || req.get_header("HTTP_X_CSRF_TOKEN")
end

Laravel supports this out of the box, and it looks like Django allows you to configure which header to use.

Rails UJS will set the header on xhr requests too, as per the security guide.

Overriding the method request_csrf_token(req) seems like a good way to solve the problem.

I will craft something using this solution.