Rails protect_from_forgery problems and warning with C#/unity3D

782 views Asked by At

I just get my hands on rails' protect_from_forgery, and I have written a simple login for my app as below:

Client-side

<h1>Login</h1>

<%= form_for :session do |f| %>
  <p>
    <%= f.label :id %><br />
    <%= f.text_field :id %>
  </p>
  <p>
    <%= f.label :pw %><br />
    <%= f.text_field :pw %>
  </p>
  <p>
    <%= f.submit %>
  </p>
<% end %>

At the server side, in my application_controller.rb I have

protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format == 'application/json' }

I have tried login from the page, and it seems OK; at least I can login. However, I'd have a few questions to ask (I am on win OS)

  1. I couldn't find any detail on the options for protect_from_forgery; I'd appreciate if anyone of any side that I can get a detailed explanation on that the options following with: null_session, if: Proc.new { |c| c.request.format == 'application/json' }

  2. How can I tell if my form is using and passing the CSRF authentication? I can see from the console in the set of params the form sent there is an 'authenticity_token', is this the one? If yes, how is it generated/defined? As I see that it is the same every time.

Also, I have another application (written in Unity3D c#) doing below, connect to the same server:

WWWForm form = new WWWForm(); 
form.AddField("id", id); 
form.AddField("pw", pw);   
WWW www = new WWW(mainUrl + "login/", form);

This time, again my client can still login, but on from the console I can see there is a warning as below

WARNING: Can't verify CSRF token authenticity   

I have googled on this, but it seems most answer is to say I should just add skip_before_filter :verify_authenticity_token, but this will just simply bypass the security check no? But I need the security check here so then it makes no sense to me...

How could I fix this and ensure that my login session is checked with protect_from_forgery?

Thanks all in advance for helping me on my questions! :)

1

There are 1 answers

4
hiveer On

You have so many questions and I will not explain each one, but to give you some prompt. First, you can find the detail explanation of protect_from_forgery from Rails API.

And also Rails Guides will give more info about CSRF.

<head>
  <%= csrf_meta_tags %>
</head>

These are used to generate the dynamic forms that implement non-remote links with :method.

You don't need to use these tags for regular forms as they generate their own hidden fields.

For AJAX requests other than GETs, extract the “csrf-token” from the meta-tag and send as the “X-CSRF-Token” HTTP header. If you are using jQuery with jquery-rails this happens automatically.