Rails / Devise - 通过json请求创建新用户

时间:2012-01-28 09:15:27

标签: ruby-on-rails devise

我想通过JSON进行新的用户注册,但是我收到了无效的真实性令牌错误。

我想不要为所有控制器打开伪造检查。有关如何覆盖registrationcontroller的任何建议吗?

这是我的代码:

class Api::MobileRegistrationsController  < Devise::RegistrationsController 
  skip_before_filter :verify_authenticity_token
  respond_to :json
  def create
    super
  end
end

路线:

Whitney::Application.routes.draw do
  resources :apps
  devise_for :users
  namespace :api do
    resources :tokens, :only => [:create, :destroy]
    resources :MobileRegistrations, :only => [:create] 
  end

我收到错误:

Routing Error
uninitialized constant Api::MobileRegistrationsController

3 个答案:

答案 0 :(得分:4)

我不能以这种方式鼓励你,因为你的应用程序很容易受到CSRF攻击。

了解CSRF的一个很好的资源:Understanding the Rails Authenticity Token

您应该在POST请求中包含authenticity_token。这在SO的一些问题中进​​行了讨论,就像那里(阅读所有答案):rails - InvalidAuthenticityToken for json/xml requests

这个想法:

  1. 使用<%= form_authenticity_token %>

  2. 检索令牌
  3. 使用令牌为您的请求添加authenticity_token POST参数。

  4. 如果您通过URI传递参数,请不要忘记编码令牌值:

    url += "&authenticity_token=" + encodeURIComponent( <%= form_authenticity_token %> );
    

答案 1 :(得分:0)

您可以构建自己的控制器,而不是从设计控制器派生。

def UserSignupApiController < ApplicationController
  skip_before_filter :authenticate_user!
  respond_to :json
  def create
    @user = User.create(params[user])
    respond_with(@user)
  end
end

我想你明白了。您只需像在Rails console中那样实例化您的用户。 我不建议采用这种做法

答案 2 :(得分:0)

为您的错误

  

路由错误未初始化的常量   API :: MobileRegistrationsController

表示您的控制器不在正确的文件夹中。 因为你正在使用

  namespace :api do
    resources :tokens, :only => [:create, :destroy]
    resources :MobileRegistrations, :only => [:create] 
  end

您需要将MobileRegistrations放入controllers / api文件夹。或者你可以使用

scope "/api" do
  resources :MobileRegistrations, :only => [:create] 
end