Ruby on Rails 4, Salesforce OAuth authentication and Restforce
In this post I’m going to explain how to add Salesforce OAuth authentication to a Rails application. Later I’ll be explaining how to use restforce gem to access Salesforce.com data on behalf of the authenticated user.
Edit I’ve updated some parts to work with the latest version of Rails at the moment (4.1.7). The code of this tutorial is here
The Stack
Salesforce
Create a connected APP in salesforce
Head to Setup/Create/Apps:
At the bottom of the screen there’s a section called Connected apps click on New:
Fill the required fields with information about your app, and check “Enable OAuth Settings”:
After the app is created take note of the “Consumer Key” and “Consumer Secret”. The terminology is from OAuth 1.0 those now are called “Client Id” and “Client Secret”.
Ruby on Rails
Open your Gemfile
and add the needed gems
The gem “slim-rails” is to use slim language for templating. I prefer it over erb because templates look lighter.
Install them running:
User model
Generate the user model.
Modify User model to interact with omniauth
We need to add this to the User model in order to update current user record when the log in is complete.
Edit the file located at /app/models/user.rb
:
Add a helper method to interact with current_user
Edit /app/controllers/application_controller.rb
, this helper will be available in your app so we can know current user data.
Create a Sessions controller
Create a Sessions controller /app/controllers/sessions_controller.rb
to manage user sessions.
Add routes
Modify your /config/routes.rb
adding this:
Create a omniauth initializer
Create an initializer /config/initializers/omniauth.rb
and add your connected app details.
Add a user widget to all pages
Remove your initial /app/views/layouts/application.html.erb
and create an application.html.slim
in the same directory with the following content:
Restforce
With the OAuth infraestructure and the current_user helper in place, restforce initialization is quite easy:
Tutorial Code
The code of this Tutorial can be found here.
Salesforce Connected app “Consumer Key” and “Consumer Secret” must be set on config/application.rb
.
Additional interaction with Restforce can be seen on controllers/home_controller.rb
.
Comments