user fails to signin when using ajax, devise and omniauth

时间:2017-04-06 17:14:11

标签: ruby-on-rails devise omniauth

trying to sign in a user with ajax, so instead of using sign_in_and_redirect I used sign_in method.

at the end of the function the signed_in_user? is true as expected, but when hitting the server again the signed_in_user? is actually false. am I missing something?

    class OmniauthCallbacksController < Devise::OmniauthCallbacksController
      respond_to :json
      def all_omniauth_providers
        @user = User.find_for_oauth(request.env["omniauth.auth"])
        if @user.persisted?
            # sign_in_and_redirect @user, :event => :authentication
            if (sign_in(@user, :event => :authentication) )
              respond_with resource, location: after_sign_in_path_for(resource)
            else
              # respond_with resource, location: root_path
            end
        else
          session["devise.#{provider}_data"] = request.env["omniauth.auth"]
          render :status => 401, :json => { :errors => alert }
        end
      end

      alias_method :facebook, :all_omniauth_providers
    end

and the javascript to connect:

  <script type="text/javascript">
      window.fbAsyncInit = function() {
          // init the FB JS SDK
          FB.init({
              appId      : '<%=Rails.application.secrets.facebook_app_id%>', // App ID from the App Dashboard
              channelUrl : '//localhost:3000/channel.html', // Channel File for x-domain communication
              status     : true, // check the login status upon init?
              cookie     : true, // set sessions cookies to allow your server to access the session?
              xfbml      : true,  // parse XFBML tags on this page?
              version    : 'v2.5'
          });

          // Additional initialization code such as adding Event Listeners goes here

      };

  (function(d, s, id){
       var js, fjs = d.getElementsByTagName(s)[0];
       if (d.getElementById(id)) {return;}
       js = d.createElement(s); js.id = id;
       js.src = "//connect.facebook.net/en_US/sdk.js";
       fjs.parentNode.insertBefore(js, fjs);
     }(document, 'script', 'facebook-jssdk'));

      $(function() {
          $('#facebook-connect').click(function(e) {
              e.preventDefault();

              FB.login(function(response) {
                if(response.authResponse) {
                  $.ajax({
                    type: 'POST',
                    url: '/users/auth/facebook/callback',
                    dataType: 'json',
                    data: {signed_request: response.authResponse.signedRequest},
                    success: function(data, textStatus, jqXHR) {
                      $('#close').click();
                      $("#share").jsSocials("option", "url", "<%=url%>?ref=" + data.id);
                      $('#loginout_button').html("<%= j button_to t('auth.logout'), destroy_user_session_path, :class=>'btn btn-default navbar-btn  navbar-left btn-xs btn-success', :method => :delete %>");
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                      $('.server_error').addClass('alert alert-danger').html("<%= t('auth.login_failed') %>");
                      shakeModal();
                    }
                  });
                }
              }
              , {scope: 'email'});

          });
      });


      $(function() {
          $('#facebook-logout').click(function(e) {
              e.preventDefault();

              FB.getLoginStatus(function(response) {
                if(response.authResponse) {
                  FB.logout();
                }
              }
              , {scope: 'email'});

          });
      });
  </script>
  <!-- end Facebook connect script -->

1 个答案:

答案 0 :(得分:0)

我花了一段时间,但问题是CSRF身份验证失败了,因为我使用的是Ajax,在设计登录后,它会更改标题中的CSRF令牌:

<%= csrf_meta_tag %>

在应用程序控制器中我有这个:     protect_from_forgery with :: null_session

我不得不跳过验证(rails 5):

protect_from_forgery with: :exception, unless: -> { request.format.json? }

我尝试使用一些技巧在从此处登录后更改csrf标头: WARNING: Can't verify CSRF token authenticity rails

但未能成功。所以这就是现在的工作方式。

相关问题