{"id":19360031,"url":"https://github.com/annastacia-dev/omniauth-rails","last_synced_at":"2026-01-25T15:02:50.035Z","repository":{"id":138768786,"uuid":"596665550","full_name":"Annastacia-dev/omniauth-rails","owner":"Annastacia-dev","description":"Rails omniauth - Google, Facebook, Twitter, LinkedIn, Github","archived":false,"fork":false,"pushed_at":"2024-08-31T08:59:42.000Z","size":92,"stargazers_count":2,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-20T09:58:03.492Z","etag":null,"topics":["facebook-auth","github-auth","google-oauth","google-oauth-login","google-oauth2","linkedin-authentication","omniauth","rails","twitter-authentication"],"latest_commit_sha":null,"homepage":"https://omiauth-rails-8588ae906061.herokuapp.com/","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Annastacia-dev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-02-02T17:16:45.000Z","updated_at":"2025-01-03T04:50:40.000Z","dependencies_parsed_at":null,"dependency_job_id":"bf727875-802b-4485-b0bc-cd48ba5e4627","html_url":"https://github.com/Annastacia-dev/omniauth-rails","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Annastacia-dev/omniauth-rails","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Annastacia-dev%2Fomniauth-rails","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Annastacia-dev%2Fomniauth-rails/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Annastacia-dev%2Fomniauth-rails/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Annastacia-dev%2Fomniauth-rails/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Annastacia-dev","download_url":"https://codeload.github.com/Annastacia-dev/omniauth-rails/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Annastacia-dev%2Fomniauth-rails/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28754807,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-25T13:59:49.818Z","status":"ssl_error","status_checked_at":"2026-01-25T13:59:33.728Z","response_time":113,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["facebook-auth","github-auth","google-oauth","google-oauth-login","google-oauth2","linkedin-authentication","omniauth","rails","twitter-authentication"],"created_at":"2024-11-10T07:16:54.181Z","updated_at":"2026-01-25T15:02:49.999Z","avatar_url":"https://github.com/Annastacia-dev.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# GOOGLE OMNIAUTH IN A RAILS APP\n\nOmniauth is a ruby gem that allows you to authenticate users with third party services. In this example we will use Google as our third party service. We will use the omniauth-google-oauth2 gem to authenticate users with Google.\n\n## Getting Started\nTo get started we will need to set up an authentication system in our rails app. For this we will use sessions. Sessions are a way to store information about a user in a cookie. This cookie is stored on the users browser and is sent back to the server with every request. This allows us to keep track of the user and their information.\nYou can check on your browser to see if you have a session cookie by going to the developer tools and looking at the cookies tab. You should see a cookie called \u003cyour_app_name\u003e_session. This is the cookie that is used to keep track of the user.\nFor chrome you can go to the developer tools by pressing F12 and then clicking on the Application tab. Then click on the Cookies tab then you should see your domain click on it and you should see your session cookie.\nFor firefox you can go to the developer tools by pressing F12 and then clicking on the Storage tab. Then click on the Cookies tab then you should see your domain click on it and you should see your session cookie.\n\n### Setting up the app\nLets start by creating a new rails app. We will call it omniauth-rails.\n```\nrails new omniauth-rails\n```\nWe will add bcrypt to our gemfile. Bcrypt is a ruby gem that allows us to hash passwords. We will use this to store the users password in the database.\n```\ngem 'bcrypt'\n```\nThen we will run bundle install to install the gem.\n```\nbundle install\n```\nNow we will create a user model. We will use the rails generator to create the model.\n```\nrails g model User username email password:digest\n```\npassword:digest will create a password_digest column in the database and add a has_secure_password method to the user model. This will allow us to use the authenticate method to check if a user has the correct password.\n```\nclass User \u003c ApplicationRecord\n  has_secure_password\nend\n```\nNow we will run the migration to create the users table in the database.\n```\nrails db:migrate\n```\nNow we will create a controller for the users. We will use the rails generator to create the controller.\n```\nrails g controller Users\n```\nWe will also need to create a controller for the sessions. We will use the rails generator to create the controller.\n```\nrails g controller Sessions\n```\n\n### Application Controller\nNow we will add the following methods to the application controller.\n```\nclass ApplicationController \u003c ActionController::Base\n\n    def index\n        if !logged_in?\n            redirect_to login_path\n        end\n    end\n\n    def current_user\n        @current_user ||= User.find(session[:user_id]) if session[:user_id]\n    end\n\n    def logged_in?\n        current_user\n    end\n\nend\n```\n\nThe index method will check if the user is logged in. If the user is not logged in we will redirect them to the login page.\nThe current_user method will check if the session[:user_id] is set. If it is set we will find the user with that id and set it to the @current_user variable. If the session[:user_id] is not set we will return nil.\nThe logged_in? method will check if the current_user method returns a user. If it does we will return true. If it does not we will return false.\n\n### Users Controller\nNow we will add the following methods to the users controller.\n```\nclass UsersController \u003c ApplicationController\n  def new\n    @user = User.new\n  end\n\n  def create\n    @user = User.new(user_params)\n    if @user.save\n      session[:user_id] = @user.id\n      redirect_to root_path\n    else\n      render :new\n    end\n  end\n\n  private\n\n  def user_params\n    params.require(:user).permit(:username, :email, :password, :password_confirmation)\n  end\nend\n```\nThe new method will create a new user object. This will be used in the form to create a new user.\nThe create method will create a new user and save it to the database. If the user is saved we will set the session[:user_id] to the id of the user. This will allow us to keep track of the user. We will then redirect the user to the root path. If the user is not saved we will render the new template.\nThe user_params method will allow us to get the parameters from the form and only allow the parameters we want to be passed in.\n\n### Sessions Controller\nNow we will add the following methods to the sessions controller.\n```\nclass SessionsController \u003c ApplicationController\n\n    def new\n       if logged_in?\n              redirect_to root_path\n         end\n    end\n\n    def create\n        @user = User.find_by(username: params[:session][:username])\n        if @user \u0026\u0026 @user.authenticate(params[:session][:password])\n            session[:user_id] = @user.id\n            redirect_to root_path\n        else\n            flash[:error] = \"Invalid username or password\"\n            redirect_to login_path\n        end\n\n    end\n\n    def destroy\n        session.delete :user_id\n        redirect_to root_path\n    end\n  \nend\n```\nThe new method will check if the user is logged in. If the user is logged in we will redirect them to the root path.\nThe create method will find the user by the username. If the user is found and the password is correct we will set the session[:user_id] to the id of the user. This will allow us to keep track of the user. We will then redirect the user to the root path. If the user is not found or the password is incorrect we will redirect the user to the login page.\nThe destroy method will delete the session[:user_id] and redirect the user to the root path.\n\n### Routes\nNow we will add the following routes to the routes.rb file.\n```\nRails.application.routes.draw do\n  root 'application#index'\n  get '/login', to: 'sessions#new'\n  post '/login', to: 'sessions#create'\n  delete '/logout', to: 'sessions#destroy'\n  get '/signup', to: 'users#new'\n  post '/signup', to: 'users#create'\nend\n```\nThe root route will go to the index method in the application controller.\nThe get '/login', to: 'sessions#new' route will go to the new method in the sessions controller.\nThe post '/login', to: 'sessions#create' route will go to the create method in the sessions controller.\nThe delete '/logout', to: 'sessions#destroy' route will go to the destroy method in the sessions controller.\nThe get '/signup', to: 'users#new' route will go to the new method in the users controller.\nThe post '/signup', to: 'users#create' route will go to the create method in the users controller.\n\n### Views\nNow we will create the views for the users and sessions controllers.\n```\nmkdir app/views/application\nmkdir app/views/users\nmkdir app/views/sessions\n```\n\n#### Application\nNow we will create the index.html.erb file in the application folder and add the following code.\n```\n\u003ch1\u003e Welcome \u003c%= @current_user.username %\u003e! \u003c/h1\u003e\n\u003c%= button_to \"Logout\", logout_path, method: :delete %\u003e\n```\nThis will display the username of the current user and a logout button.\n\n#### Users\nNow we will create the new.html.erb file in the users folder and add the following code.\n```\n\u003ch1\u003e Sign up for a new account \u003c/h1\u003e\n\u003c%= form_for @user do |f| %\u003e\n    \u003c%= f.label :username %\u003e\n    \u003c%= f.text_field :username %\u003e\n    \u003c%= f.label :email %\u003e\n    \u003c%= f.text_field :email %\u003e\n    \u003c%= f.label :password %\u003e\n    \u003c%= f.password_field :password %\u003e\n    \u003c%= f.label :password_confirmation %\u003e\n    \u003c%= f.password_field :password_confirmation %\u003e\n    \u003c%= f.submit \"Sign up\" %\u003e\n\u003c% end %\u003e\n\n\u003cp\u003eAlready have an account? \u003c%= link_to \"Login\", login_path %\u003e\u003c/p\u003e\n```\nThis will display a form to create a new user. It will also display a link to the login page.\n\n#### Sessions\nNow we will create the new.html.erb file in the sessions folder and add the following code.\n```\n\u003ch1\u003eLogin to your account\u003c/h1\u003e\n\u003c% if flash[:error] %\u003e\n    \u003cp\u003e\u003c%= flash[:error] %\u003e\u003c/p\u003e\n\u003c% end %\u003e\n\n\n\u003c%= form_for :session, url: login_path do |f| %\u003e\n    \u003c%= f.label :username %\u003e\n    \u003c%= f.text_field :username %\u003e\n    \u003c%= f.label :password %\u003e\n    \u003c%= f.password_field :password %\u003e\n    \u003c%= f.submit \"Login\" %\u003e\n\u003c% end %\u003e\n\n\u003cp\u003eDon't have an account? \u003c%= link_to \"Sign up\", signup_path %\u003e\u003c/p\u003e\n```\nThis will display a form to login to an account. It will also display a link to the signup page.\n\nYour application should now be able to create a new user, login to an existing user, and logout of a user.\n\n# GOOGLE OAUTH\nFirst we will need to create a new project in the google developer console.\nGo to [https://console.developers.google.com/](https://console.developers.google.com/) and under select a project click on new project.\nGive your project a name and click create. eg. omniauth-rails\nWhile on the project under APIs \u0026 Services click on OAuth consent screen.\nSet the user type to external and click create.\nOn the next page fill out the information and click save.\nThe app name, user support email, and developer contact information are required.\nIf your application is in production you will need to add your application url to the authorized domains.You can also upload your app logo, a privacy policy url, and a terms of service url.\nClick on save and continue.\nOn the scopes page, at the moment we don't need to add any scopes. Click on save and continue.\nScopes are used to limit the amount of information that is shared with the application. For example, if you only want the user's email address you can add the scope https://www.googleapis.com/auth/userinfo.email. If you want the user's email address and their profile picture you can add the scope https://www.googleapis.com/auth/userinfo.profile.\nClick on save and continue.\nOn the test users page you can add test users to your application.This means that only the email addresses that you add will be able to login to your application.I will not be adding any test users.\nClick on save and continue.\nOn the summary page you can see all of the information that you have entered. Click on back to dashboard.\nOn the side dashboard click on credentials and then click on create credentials.\nSelect OAuth client ID and under application type select web application.\nGive your application a name and add http://localhost:3000/auth/google_oauth2/callback to the authorized redirect URIs.\nClick on create.\nYou will now see your client ID and client secret.\nSave this as we will need them later.\n\n### Back to our Rails application\nNow we will add the following to the Gemfile.\n```\ngem 'omniauth'\ngem 'omniauth-google-oauth2'\ngem 'dotenv-rails'\ngem 'omniauth-rails_csrf_protection'\n```\ngem 'omniauth' is the main gem that we will be using.\ngem 'omniauth-google-oauth2' is the gem that will allow us to use google oauth.\ngem 'dotenv-rails' is the gem that will allow us to store our client ID and client secret in a .env file.\ngem 'omniauth-rails_csrf_protection' is the gem that will protect against CSRF attacks.\n\n\nThen run bundle install.\n```\nbundle install\n```\nNow we will create a .env file in the root directory of our application.\n```\ntouch .env\n```\nNow we will add the following to the .env file.\n```\nGOOGLE_CLIENT_ID=your_client_id\nGOOGLE_CLIENT_SECRET=your_client_secret\n```\nRemember to add your .env file to your .gitignore file.\nSyntax: Note that there are no quotes around the client ID and client secret and no spaces around the equal sign.\n\nNow we will create a new initializer file in the config/initializers directory.\n```\ntouch config/initializers/omniauth.rb\n```\nNow we will add the following to the omniauth.rb file.\n```\nRails.application.config.middleware.use OmniAuth::Builder do\n    provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'],\nend\n```\nThis is a middleware that will allow us to use omniauth with our application.\nThe provider method will allow us to use google oauth.\nYou can also use other providers such as facebook, twitter, github, etc.\nYou can configure several options, which you pass in to the provider method via a hash:\n```\nprovider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'],\n    {\n        scope: 'email, profile', -- This will allow us to get the user's email address and profile picture.\n        prompt: 'select_account', -- This will allow the user to select which account they want to login with.\n        image_aspect_ratio: 'square', -- This will make sure that the profile picture is a square.\n        image_size: 50, -- This will make sure that the profile picture is 50x50 pixels.\n    }\n```\nTo read more about gem 'omniauth-google-oauth2' go to [https://github.com/zquestz/omniauth-google-oauth2](https://github.com/zquestz/omniauth-google-oauth2).\n\nRemember to restart your server after making any changes to the omniauth.rb file.\n\nCreate a migration to add a uid and provider column to the users table.\n```\nrails g migration AddUidAndProviderToUsers uid provider\n```\nThen run the migration.\n```\nrails db:migrate\n```\n\n\nLet's add a new omniauth action to the sessions controller.\n```\ndef omniauth\n        @user = User.find_or_create_by(uid: request.env['omniauth.auth']['uid'], provider: request.env['omniauth.auth']['provider']) do |u|\n            u.username = request.env['omniauth.auth']['info']['name']\n            u.email = request.env['omniauth.auth']['info']['email']\n            u.password = SecureRandom.hex(10)\n        end\n        if @user.valid?\n            session[:user_id] = @user.id\n            redirect_to root_path\n        else\n            render :new\n        end\nend\n```\nThe auth hash is a hash that contains all of the information that we get from the provider.\n```\n{\n  \"provider\" =\u003e \"google_oauth2\",\n  \"uid\" =\u003e \"100000000000000000000\",\n  \"info\" =\u003e {\n    \"name\" =\u003e \"John Smith\",\n    \"email\" =\u003e \"john@example.com\",\n    \"first_name\" =\u003e \"John\",\n    \"last_name\" =\u003e \"Smith\",\n    \"image\" =\u003e \"https://lh4.googleusercontent.com/photo.jpg\",\n    \"urls\" =\u003e {\n      \"google\" =\u003e \"https://plus.google.com/+JohnSmith\"\n    }\n  },\n  ...\n}\n```\nYou can read more about the auth hash at [https://github.com/zquestz/omniauth-google-oauth2](https://github.com/zquestz/omniauth-google-oauth2).\nWe can access the information by using the hash syntax.\nFor example, if we want to get the user's email address we can use request.env['omniauth.auth']['info']['email'].\nIn the omniauth action in the sessions controller we are using the find_or_create_by method to find the user by their uid and provider or create a new user if they don't exist.\nWe are also using the SecureRandom.hex(10) to set the password.This sets the password to a random string of 10 characters.\n\nNow we will add a new route to the routes.rb file.\n```\nget '/auth/:provider/callback', to: 'sessions#omniauth'\n```\nThis route will allow us to use the omniauth action in the sessions controller.\nWe use ':provider' to make the route dynamic.This means that we can use this route for any provider. eg facebook, twitter, github, etc.\n\nNow we will add a new button to the login page.\nIn the app/views/sessions/new.html.erb file add the following.\n```\n\u003ch3\u003e Or login with Google\u003c/h3\u003e\n\u003c%= button_to \"Login with Google\", \"/auth/google_oauth2\" %\u003e\n```\nThis will create a button that will allow the user to login with google.\nA button_to is a form that will send a post request to the specified path.\n\nOur application is now ready to use google oauth.\nTo test it out, run the rails server and go to [http://localhost:3000/login](http://localhost:3000/login).\n\nCheck out the [live site](https://railsomniauth.onrender.com) here.\n\nThat's it for this tutorial.Thank you for reading.\nRemember to check out the source code on github at [https://github.com/Annastacia-dev/omniauth-rails](https://github.com/Annastacia-dev/omniauth-rails).\nFeel free to leave any comments or questions below or reach out to me on email at [annetotoh@gmail.com](mailto:annetotoh@gmail.com).\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fannastacia-dev%2Fomniauth-rails","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fannastacia-dev%2Fomniauth-rails","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fannastacia-dev%2Fomniauth-rails/lists"}