2012-01-28 88 views
9

我想通过JSON做一个新的用户注册,但我得到一个无效的真实性令牌错误。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 

回答

0

你可以BUIL自己的控制器,它不是从有一项派生控制器。

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中那样实例化你的用户。 虽然我不推荐这种做法

3

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

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

你还是在您的POST请求authenticity_token。这是在SO一些问题的讨论,好像有(读所有的答案):rails - InvalidAuthenticityToken for json/xml requests

的想法:

  1. 检索令牌<%= form_authenticity_token %>

  2. 一个authenticity_token POST PARAM添加到您的请求令牌。

如果通过URI通过帕拉姆,不要忘了编码的令牌值:

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

对于您的错误

Routing Error uninitialized constant Api::MobileRegistrationsController

它表明你的控制器是不是在正确的文件夹 由于您使用

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

你需要把你的MobileRegistrations到控制器/ API文件夹中。或者您可以使用

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