简体   繁体   中英

Devise ajax sign_in

I was trying to make a ajax sign_in via devise , I follow this tutorial .

I've successfully created a ajax sign_up . Here is my registrations_controller.rb

class RegistrationsController < Devise::RegistrationsController
  respond_to :json
  skip_before_filter :verify_authenticity_token, :only => :create
end

It works fine but fail in sign_in .

Here is my session_controller.rb

class SessionsController < Devise::SessionsController
  respond_to :json
end

The parameter and path would be like this

Path: /users/sign_in Parameter:

{
  "user": 
  {
    "email": "123@gmail.com",
    "password":"12345678",
    "remember_me":"1"
  },
  "commit":"Log in"
}

But I got this error.

在此处输入图片说明

Update

I still got 401 Unauthorized . I've tried the following way.

1.Editing application_controller.rb the protect_from_forgery to protect_from_forgery with: :null_session

2.Add skip_before_filter :verify_authenticity_token, :only => :create in sessions_controller.rb

3.Modify my ajax to this

$.ajax ({
      headers: {
        'X-Transaction': 'POST Example',
        'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
      },
      url: "sign_in",
      type: "POST",
      dataType: 'json',
      data: {
        "user": {"email": "example@gmail.com", "password": "password"}
      },
      success: function(msg){
        console.log("Success");
      },
      error: function(msg) {
        console.log("Errors");
      }
});

However, all of them threw the same error.

Started POST "/users/sign_in" for ::1 at 2016-12-14 01:13:09 +0800
Processing by SessionsController#create as JSON
  Parameters: {"user"=>{"email"=>"example4@gmail.com", "password"=>"[FILTERED]"}, "commit"=>"Log in"}
  User Load (0.3ms)  SELECT  `users`.* FROM `users` WHERE `users`.`email` = 'example4@gmail.com' ORDER BY `users`.`id` ASC LIMIT 1
Completed 401 Unauthorized in 2ms (ActiveRecord: 0.3ms)

I believe the CSRF token is missing... it's also stated in the tutorial you are following: http://blog.andrewray.me/how-to-set-up-devise-ajax-authentication-with-rails-4-0/#maketheajaxrequests

Try editing in your application_controller.rb the protect_from_forgery to protect_from_forgery with: :null_session

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM