DEV Community

reyes2981
reyes2981

Posted on

what i learned last week: ruby on rails - omniauth -google_auth2

In Norway, a firm handshake is preferred, people will most often shake hands when agreeing on deals, in private and business relations. In our neck of the woods a traditional handshake is firm, executed with the right hand, with good posture and eye contact. Throughout modern history the handshake has played a huge role in everything from major political events to that nerve wrecking "meeting their parents" dinner. In this blog I will be answering the following questions: What is Oauth? What is Omniauth? What is Devise? What do they have to do with a handshake?

Lets get to it!

For this project we were tasked with creating a Ruby on Rails program that implements third party login/signup. I will be honest, when I first read that requirement I got nervous. Now, at the end of this OAuth bridge I can say it's not as complicated as it seems but it's still tricky.

In technical words, OAuth, is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords. One of the benefits of implementing this standard into a program is it gets rid of the need to store confidential user information, like passwords, to a server. Instead, a third party provider (Google, Github, Facebook) handles the authentication for you, the developer.

OAuth 2.0

Remember the handshake I mentioned earlier? Well this is where it comes into play. For OAuth to work properly an agreement needs to be made between the user, OAuth server and resource server. If all "hands are shook" and all "I's have been dotted" the resource server will return the requested resource to the user.

Setting up Google Client ID and Google Client secret

Step 1. Head over to Google Developer Console

Step 2. Utilize the menu on the right side of the screen to navigate to APIs && Services

Step 3. Click on credentials

Step 4. Navigate the right side of the webpage click "Create Project"

Step 5. Google will direct you to a new page where you will need to enter your projects name
Alt Text

Step 6. Once you choose a project name and click "create" you will be redirected to the following page
Alt Text

Step 7. Utilize the menu on the right side of the screen to navigate to Credentials button and click it. You will then be redirected to a new page.

Step 8. At the top of the page click "Create Credentials" and a dropdown menu will appear. You will need to click on "OAuth client ID"
Alt Text

Step 9. Google might ask you to configure a consent screen. I would recommend choosing "External" where it asks to choose a User Type. Once you have made a selection you will be redirected to the following page. You will fill out the App name once and your email address twice in this page (nothing else) and save.
Alt Text

Step 10. skip over the the preceding steps until you get to the summary and click "save". Now with that all set up lets again...

Step 11. Utilize the menu on the right side of the screen to navigate to credentials and click on it.

Step 12. At the top of the page click "Create Credentials" and a dropdown menu will appear. You will need to click on "OAuth client ID."
Alt Text

step 13. You will be redirected to choose an application type, enter your project name and provide an authorized redirect URI. Once you have saved the information a pop up will appear with your Google client ID and Google client Secret.

Authorized Redirect URI Example: http://localhost:3000/auth/google_oauth2/callback

Alt Text

STOP!

It is imperative that you don't share the above information with anyone. Our "handshake" with Google will not happen if you forget your client id/client password or worse it could get into the wrong hands.

Backend Process

Now that we have our Google Client ID and Secret we can start wiring everything up in our program.

Ruby Gems Required:

gem 'omniauth'
gem 'omniauth-rails_csrf_protection'
gem 'omniauth-google-oauth2'
gem 'dotenv'
=> this is added to the development environment

After the gemfile is all set up the next step is to take care of the environment variables.

Please note, this part of the process is another important part of the "handshake."

First you will go to the root of your programs directory in the terminal and type in touch .env. This will create an environment file in the root of your project.

Once you have have confirmed that the file is in fact in your root directory head over to the .gitignore file, also in the root directory, and scroll down to where it says "Ignore master key for decrypting credentials and more." In that section type in .env and save the file. This process ensures that this file will never be committed to your remote Github repository. Why is it important that we don't save this .env file to our remote repository? Well because this is where we will be saving the Google Client ID and Secret that we created earlier in the blog.

In the .env file you will enter the aove information in the following format:

GOOGLE_CLIENT_ID=<google-client-id>
GOOGLE_CLIENT_SECRET=<google-client-id>

Next, you will head over to config\initializers and Create a new file called omniauth.rb. Within that file you will code the following middleware (please note this is standard syntax) -

Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV['GOOGLE_CLIENT_KEY'], ENV['GOOGLE_CLIENT_SECRET']
end

Note that the above environment variable names MUST match the names of the environment variables in the .env file we created earlier.

Once the above is completed, head over to the routes file in your config directory. Here we will need to set up a route for when the third party provider responds back to our server:

get "/auth/google_oauth2/callback" => 'sessions#omniauth'

The next step I took was to head over to my Sessions controller and created two actions, "omniauth" and "private"

def omniauth
        #find_or_create a customer using the attribute auth
        @customer = Customer.find_or_create_by(email: auth["info"]["email"]) do |customer|
          customer.full_name = auth["info"]["name"]
          customer.password = SecureRandom.hex(10)
        end
        if @customer.save
          session[:customer_id] = @customer.id
          redirect_to customer_path(@customer).error.inspect
        else
          redirect_to '/'
        end
    end

private

  def auth
    request.env['omniauth.auth']
  end
Enter fullscreen mode Exit fullscreen mode

The above code makes it possible to see Google's response to the our servers request to access customer information.

Once you have implemented the above code you will be all set! Go to your terminal, type in `dotenv rails server and go to your your localhost via a browser.

Cuts-4-Less GitHub Repository

Sources
https://en.wikipedia.org/wiki/OAuth
https://en.wikipedia.org/wiki/Handshake

Top comments (0)