In this post I will explain how to configure Rails to perform single sign-on authentication using Oauth2 and your hosted WordPress site as an authentication provider.
I’ve worked on a few projects lately where there was a need to integrate a Rails site with an existing WordPress site in a Single Sign On fashion but without authenticating against a central auth store or use of an SSO appliance. It is very easy to turn an existing WordPress installation into an OAuth provider and skip the hassle of maintaining a central authentication store or a conversion effort for users already using your WordPress blog.
In order to turn our existing wordpress installation into an Oauth2 provider we first have to install the WordPress Oauth2 Complete plugin. The official plugin in the WordPress plugins repository is missing some recent enhancements so I recommend installing from the 1.0.4 release on github: https://github.com/justingreerbbi/wordpress-oauth/archive/1.0.4.zip
/wp-content/plugins/directory or use the built in plugin install by WordPress
rails new omniauth-wordpress-oauth2-plugin-example . --database=sqlite3 -T
rails g devise:install
rails g devise user rails db:migrate
Install Oauth2 provider plugin for your wordpress site:
Create client entry for your rails app with the callback key set to:
Save the generated key & secret for next step
Add provider to devise initializer
config/routes.rb to add omniauth_callbacks controller
Easiest to just create the class
app/controllers/omniauth_callbacks_controller.rb instead of running generator.
Update user to be omniauthable
Update User model to find users by oauth provider data:
Now when an authenticated resource is requested on your rails site, the user will be redirected to the wordpress auth provider to login. When the user has authenticated, they will be redirected back to your rails application and your app will receive a hash of user data passed from the authentication source:
Demo Application: https://github.com/jwickard/omniauth-wordpress-oauth2-plugin-example
That’s it! Thanks!