Rails/Devise - 通过 json 请求创建新用户 [英] Rails/Devise - Creating new users via json request
问题描述
我想通过 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 : Understanding the Rails Authenticity Token
您应该在 POST 请求中包含 authenticity_token
.这在关于 SO 的一些问题中进行了讨论,例如(阅读所有答案):rails - InvalidAuthenticityToken for json/xml requests
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
想法:
使用
<%= 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屋!