开发者

How do I get Ruby on Rails to work with ASIHTTPRequest?

I am creating an iOS application with a Ruby on Rails backend. I've got my logic setup and working in Rails, and have verified by testing in a web browser. My Rails application will not respond properly to my iOS application, saying something about an authenticity token.

I have setup an authenticity token in applicat开发者_Python百科ion.rb with the following code (I did a server reboot after adding this):

protect_from_forgery :secret => 'some_secret_here'

I'm passing the authenticity token from iOS to Rails with ASIHTTPRequest using the following code:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:@"some_secret_here" forKey:@"authenticity_token"];
[request setPostValue:@"some value" forKey:@"some_parameter"];
[request setDelegate:self];
[request startAsynchronous];

Is there anything I'm missing or doing wrong?

This same code works fine with allow_forgery_protection set to false, so I assume the error lies in how I'm trying to pass the authenticity token.


The authenticity token is different for each page/request, so you need to find a way to send it through the pipe some other way.

Maybe try sending it via headers, like so:

class ApplicationController < ActionController::Base
    before_filter :send_form_authenticity_token

    private
      def send_form_authenticity_token
        response.headers['X-Authenticity-Token'] = form_authenticity_token
      end
end

On the response callback of your first (and following) request(s), you need to do:

NSString *authenticityToken = [[request responseHeaders] objectForKey:@"X-Authenticity-Token"];

This implies that the first request you do is a GET one.

Would be better to have a global state variable, but this is the basic concept.

By the way, and just so you know, you don't need forgery protection if your rails application is just a backend sorts of app.

Forgery protection is there to avoid XSS attacks, and that wouldn't happen on the iPhone.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜