Rails/Devise - Creating new users via json request

前端 未结 3 1723
心在旅途
心在旅途 2020-12-24 09:34

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 sugg

相关标签:
3条回答
  • 2020-12-24 09:55

    You could buil your own controller that does not derive from a devise controller.

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

    I think you get the idea. You just instantiate your User just like you would do in Rails console. I do not recommend this kind of practice though

    0 讨论(0)
  • 2020-12-24 10:02

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

    A good resource to understand CSRF : Understanding the Rails Authenticity Token

    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

    The idea :

    1. Retrieve the token with <%= form_authenticity_token %>

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

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

    url += "&authenticity_token=" + encodeURIComponent( <%= form_authenticity_token %> );
    
    0 讨论(0)
  • 2020-12-24 10:03

    For your error

    Routing Error uninitialized constant Api::MobileRegistrationsController

    it indicates your controller is not in the correct folder. Because you are using

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

    You need to put your MobileRegistrations into controllers/api folder. or you can use

    scope "/api" do
      resources :MobileRegistrations, :only => [:create] 
    end
    
    0 讨论(0)
提交回复
热议问题