Rails / Devise - 通过json请求创建新用户 [英] Rails/Devise - Creating new users via json request

查看:97
本文介绍了Rails / Devise - 通过json请求创建新用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to do a new user signup via JSON but I get an invalid authenticity token error.

我不想对所有控制器进行伪造检查。有关如何覆盖注册控制器的建议?

I would like to not turn the forgery check for all controller. Any suggestions on how to override the registrationcontroller to do this?

这是我的代码:

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攻击。

I can't encourage you in this way, because your app will be vulnerable to CSRF attacks.

了解CSRF的好资源:了解Rails真实性令牌!

A good resource to understand CSRF : Understand Rails Authenticity Token!

您应该在您的POST请求中包含 authenticity_token 。这在SO的一些问题中有所讨论,像那里(阅读所有答案): rails - 对于json / xml请求的无效AuthhenticityToken

You should rather include the authenticity_token in your POST request. This is discussed in some questions on SO, like there (read all the answers) : rails - InvalidAuthenticityToken for json/xml requests

想法:


  1. 使用<%= form_authenticity_token%>

添加 authenticity_token 使用令牌对你的请求进行POST参数。

Add a authenticity_token POST param to your request with the token.

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

If you pass the param by URI, don't forget to encoded the token value :

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

这篇关于Rails / Devise - 通过json请求创建新用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆