Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Omniauth without Devise
Yaroslav Shmarov
Yaroslav Shmarov

Posted on • Originally published atblog.corsego.com on

     

Omniauth without Devise

Previously I’ve coveredGithub omniauth with Devise, andGithub omniauth with Devise without email registration.

An evensimpler solution would be to sign in via a social login providerwithout Devise at all! Here’s the easiest way to do it.

First, add theomniauth gems:

# Gemfilegem'omniauth-github',github:'omniauth/omniauth-github',branch:'master'gem"omniauth-rails_csrf_protection","~> 1.0"
Enter fullscreen modeExit fullscreen mode

Add your social provider API credentials:

# https://github.com/omniauth/omniauth# https://github.com/settings/applications/new# echo > config/initializers/omniauth.rb# config/initializers/omniauth.rbRails.application.config.middleware.useOmniAuth::Builderdoprovider:github,"GITHUB_ID","GITHUB_SECRET"end
Enter fullscreen modeExit fullscreen mode

Create a user model. We will also add a few static pages:

  • /landing_page that can be accessed without authentication
  • /dashboard that requires authentication
railsgcontrollerstatic_pageslanding_pagedashboardrailsgmodelUseremailgithub_uid
Enter fullscreen modeExit fullscreen mode

Routes:

# config/routes.rbroot'static_pages#landing_page'get'dashboard',to:'static_pages#dashboard'get'auth/github/callback',to:'sessions#create'delete'logout',to:'sessions#destroy'# get 'login', to: redirect('/auth/github'), as: 'login'
Enter fullscreen modeExit fullscreen mode

Gems like devise provide some default methods, that we will have to add on our own now:

  • def current_user - get the current user from session params.
  • def user_signed_in? - check if there is a current user.
  • def require_authentication - to restrict controller actions for non-authenticated users.
  • helper_method :current_user - to makecurrent_user available in views.
# app/controllers/application_controller.rbclassApplicationController<ActionController::Baseprotect_from_forgerywith: :exceptionhelper_method:current_userdefrequire_authenticationredirect_toroot_path,alert:'Requires authentication'unlessuser_signed_in?enddefcurrent_user@current_user||=User.find(session[:user_id])ifsession[:user_id]enddefuser_signed_in?# converts current_user to a boolean by negating the negation!!current_userendend
Enter fullscreen modeExit fullscreen mode

The button to/auth/github will redirect to the github login page.

# app/views/layouts/application.html.erb<%= link_to 'Home', root_path %><% if current_user %>  <%=current_user.email%>  <%= link_to 'Dashboard', dashboard_path %><%= button_to 'Logout', logout_path, method: :delete, data: { turbo: false } %><% else %>  <%=button_to"Sign in with Github","/auth/github",data:{turbo:false}%><% end%>
Enter fullscreen modeExit fullscreen mode

After successful authentication, the user should be redirected tosessions#create withrequest.env['omniauth.auth'].

# app/controllers/sessions_controller.rbclassSessionsController<ApplicationControllerdefcreate@user=User.from_omniauth(request.env['omniauth.auth'])if@user.persisted?session[:user_id]=@user.idredirect_todashboard_path,notice:"Logged in as#{@user.email}"elseredirect_toroot_url,alert:'Failure'endenddefdestroysession[:user_id]=nilredirect_toroot_pathendend
Enter fullscreen modeExit fullscreen mode

from_omniauth will find the usersemail anduid in the data provided by github, and find or create the user.

# app/models/user.rbclassUser<ApplicationRecordvalidates:github_uid,presence:true,uniqueness:truevalidates:email,format:{with:URI::MailTo::EMAIL_REGEXP},presence:true,uniqueness:truedefself.from_omniauth(access_token)github_uid=access_token.uiddata=access_token.infoemail=data['email']User.find_or_create_by(email:,github_uid:)endend
Enter fullscreen modeExit fullscreen mode

Finally, require authentication to visit/dashboard:

# app/controllers/static_pages_controller.rbclassStaticPagesController<ApplicationControllerbefore_action:require_authentication,only: :dashboarddeflanding_pageenddefdashboardendend
Enter fullscreen modeExit fullscreen mode

That’s it! Now you can use omniauth without devise!

Top comments(4)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
ahmednadar profile image
Ahmed Nadar
Web developer use Ruby on Rails stack , Hotwire, StimulusJs. | Technical writer.
  • Location
    Toronto
  • Work
    Rails and forn-end developer and technical writer.
  • Joined

Nice article as usual.
I have noticed many apps are using different authanitcation way these days.
Do you think Rails apps should implement authanitcations without Devise

CollapseExpand
 
superails profile image
Yaroslav Shmarov
I write about different Ruby on Rails topics. Check it out!
  • Email
  • Location
    Chernihiv, Ukraine
  • Education
    Université Clermont Auvergne
  • Work
    Senior Ruby on Rails engineer, Bearer.com
  • Joined

It really depends on what you are building. For many cases omniauth-only would be enough.

Sometimes, getting a confirmed email address can be much more valuable, than having an omniauth user account.

I think that devise via email/password + omniauth still stays the most versatile approach.

CollapseExpand
 
idd profile image
Ivo Di
  • Joined

After trying an official omniauth and devise and omniauth-google-oauth2 docs i couldn't make it all working. But thanks for your article I finally did what I wanted.
❤️

CollapseExpand
 
superails profile image
Yaroslav Shmarov
I write about different Ruby on Rails topics. Check it out!
  • Email
  • Location
    Chernihiv, Ukraine
  • Education
    Université Clermont Auvergne
  • Work
    Senior Ruby on Rails engineer, Bearer.com
  • Joined

wow, I'm glad it helped you!

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I write about different Ruby on Rails topics. Check it out!
  • Location
    Chernihiv, Ukraine
  • Education
    Université Clermont Auvergne
  • Work
    Senior Ruby on Rails engineer, Bearer.com
  • Joined

More fromYaroslav Shmarov

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp