Authenticating Google Users with Devise and OmniAuth in Rails
Posted by Auran Buckles on February 28, 2017
While building authentication processes from the ground up can prevent incompatibilities that can be hard to debug, sometimes we prefer the convinience of relying on gems built by others. Devise and OmniAuth are classic gems that authenticate through internal databases and external providers. These libraries, being open sourced, have withstood lots of trials and errors and are very powerful tools if you get it right.
To follow along with this tutorial, you will have to install the following gems:
For storing global variables in the environment, I recommend using dotenv, although there are many other options out there as well. This will help keep your Google client ID and client secret neat and easily accessible.
The process of initializing and configuring Devise and OmniAuth is pretty self-explanatory in the docs, so I’ll skip over that. The configuration for Devise to be used with Google OAuth 2.0 is as follows:
Then in the model for the users (here, the User model), add Google as a provider for Omniauth and a from_omniauth class method to assign the returned values from the API call to attributes of the User class.
Then we can define the callback actions in the controller, using the corresponding google_oauth2 method that calls from_omniauth on the User class.
Google’s OAuth access token expires every 3,600 seconds. In order for the user to continue using the app, we will have to refresh the access token that’s stored in the database (user.access_token) every time the user signs in and when calling on APIs within the app.
Lastly, double check to make sure you have the paths user_google_oauth2_omniauth_authorize and user_google_oauth2_omniauth_callback. Now, a link to “Sign in with Google” should automatically be generated on the sign in page that leads to the Google Sign In form.