0

我正在使用 Ruby on Rails 3,我想知道如何使用从 RoR 应用程序到另一个 RoR 应用程序的 HTTP POST 请求来处理 AuthenticityToken 值。在这种情况下,如果他/她提供了正确的值和值,我的目标是提交一个登录表单并以JSON格式返回用户信息。emailpassword

我在这个 URL 有一个 RoR 应用程序

pjtnam.com

以及此 URL 上的另一个 RoR 应用程序

users.pjtname.com

pjtname.com如果我像这样从应用程序向应用程序发出 HTTP POST 请求users.pjtname.com(在此示例中,我使用Typhoeus gem

response = Typhoeus::Request.post("http://users.pjtname.com/authentications",
             :params => {
               :new_authentication => {
                 :email    => email,
                 :password => password
               }
             }
           )

我得到这个回应

<h1>
  ActionController::InvalidAuthenticityToken
    in AuthenticationsController#create
</h1>
<pre>ActionController::InvalidAuthenticityToken</pre>

那么,如何以安全的方法\模式处理 AuthenticityToken 值? 我想知道应用程序何时位于同一台服务器上以及何时不在。

http://users.pjtname.com/authentications/new我有以下用于登录用户的表格:

<%= form_for(:new_authentication) do |f| %>
  <%= f.label :email %>
  <%= f.label :password %>

  <%= f.submit "Sign in" %>
<% end %>

在 authentications_controller.rb 我有

def create
  # Note ':authentication' symbol is different than ':new_authentication' seen in HTTP POST parameters and in the above form
  @authentication = Authentication.new(params[:authentication])

  @account = Account.sign_in_account(params[:new_authentication][:email], params[:new_authentication][:password])

  ...

  respond_to do |format|
    format.html {
      redirect_to @account
    }
    format.js {
      render(:update) { |page|
        page.redirect_to @account
      }
    }
    format.json {
      render :json => @account
    }
  end
end

在 routes.rb 我有

  resources :authentications do #, :path => "authentication" do
    member do
      get  'confirm_authentication'
      post 'confirm_authentication'
    end
  end


@idlefingers答案的更新


要求

Typhoeus::Request.post("http://users.pjtname.com/authentications/new",
# or
# Typhoeus::Request.post("http://users.pjtname.com/authentications",
   :headers => {"Content-Type" => "application/json"},
   :params => { ... } # Same parameters as above
   }
 )

回复

<h1>
  StandardError
</h1>
<pre>Invalid JSON string</pre>

要求

Typhoeus::Request.post("http://users.pjtname.com/authentications/new.json",
   :params => { ... } # Same parameters as above
   }
 )

回复

<h1>Routing Error</h1>
<p><pre>No route matches &quot;/authentications/new.json&quot;</pre></p>
4

1 回答 1

0

看起来它没有发送具有正确内容类型的请求。如果内容类型是 application/xml 或 application/json,Rails 应该跳过真实性令牌检查,这样它就可以很好地使用 API,而不必完全禁用真实性令牌。

我不知道 Typhoeus gem,但看起来您可能只需要在 url 中添加“.json”或“.xml”(取决于您实现的 API),或者可能需要将其作为标题哈希中的选项。

于 2011-03-01T11:31:42.503 回答