Rails / Devise – 通过json请求创建新用户
我想通过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
我不能以这种方式鼓励你,因为你的应用程序很容易受到CSRF攻击。
理解CSRF的一个很好的资源: 理解Rails真实性令牌
您应该在POST请求中包含authenticity_token
。 这在SO的一些问题中讨论过,比如那里(阅读所有答案): rails – 用于json / xml请求的InvalidAuthenticityToken
想法:
-
使用
<%= form_authenticity_token %>
检索令牌 -
使用令牌向您的请求添加
authenticity_token
POST参数。
如果您通过URI传递参数,请不要忘记编码令牌值:
url += "&authenticity_token=" + encodeURIComponent( <%= form_authenticity_token %> );
您可以构建自己的控制器,而不是从设计控制器派生。
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
那样实例化您的用户。 我不推荐这种做法
为了你的错误
路由错误未初始化的常量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