Using WordPress authentication for a Rails App – SSO Between from Rails to WordPress

We have a customer that wants to use their current WordPress site at the “source” for their user table.

(If it makes a difference, the rails app will be the primary app interface for a web front end as well as an iOS and Android front ends.)

Read More

So, the user will login through the Website and the idea is that an API call would be made to WordPress with the email/pwd. It would return an authentication successful. I would then issue a token or something like this to the Mobile platforms to allow them continued access.

Any thoughts on how to make the authentication piece work between rails -> wordpress?

Related posts

Leave a Reply

1 comment

  1. In case anyone else wants to accomplish the same thing. Here is how I solved the problem. First, my wordpress instance and rails instances are sitting on the same box, which makes this solution viable.

    1) I am using devise for authentication on the rails side. I have created an override for the “authenticate!” method, which checks wordpress.

    require 'devise/strategies/authenticatable'
    
    module Devise
      module Strategies
        class DeviseOverride < Authenticatable
          def valid?
            true
          end
    
          def authenticate!
            if params[:user]
              user = User.find_by_email(params[:user][:email])
              # user = User.first
              if user # && user.encrypted_password == params[:user][:password]
                #check password with WordPress to verify it is a good user
                result = WordPressApi.verify_user(params[:user][:email], params[:user][:password])
    
                if result
                  success!(user)
                else
                  fail!("Couldn't verify your login. Please try again.")
                end
              else
                fail!("Could not log in")
              end 
            else
              fail!("")
            end 
          end 
        end 
      end 
    end
    
    Warden::Strategies.add(:local_override, Devise::Strategies::DeviseOverride)
    

    2) This calls a simple method where I just call over to the wordpress instance to verify the user exists. (I was trying to find a way check the DB table directly, but the WP password hashing isn’t something I wanted to tackle)

    3) On the wordpress side (along with some other stuff):

    $user = get_user_by('email', $email);
            // print $user->data->user_email;
            if ($user && wp_check_password( $pwd, $user->data->user_pass, $user->ID) )
                return_json_success('Valid User', 'user', $user);
            else{
                return_json_error('Passwords do not match', 200);
                // print "Password: {$pwd}, User: {$user} UserPass: {$user->data->user_pass}  UserID: {$user->ID}";
                // print 'Passwords do not match';
            }