TIL: How to use OmniAuth with Passwordless

Henrik Hauge Bjørnskov
1 min readJan 20, 2024

Using OmniAuth with Devise is popular and widely used. However, OmniAuth can also be used standalone with other authentication solutions, such as Passwordless.

Add the gem to your Gemfile, including the extra providers you want to support:

gem 'omniauth'
gem 'omniauth-rails_csrf_protection'

Add the routes needed for OmniAuth to handle the callbacks and failures that might occur:

get 'auth/:provider/callback', to: 'omni_auth#create'
get 'auth/failture', to: 'omni_auth#failure'

Create the OmniAuthController, which handles authentication with Passwordless when a callback is returned:

# frozen_string_literal: true

class OmniAuthController < ApplicationController
include Passwordless::ControllerHelpers

def create
user = User.from_omni_auth(request.env['omniauth.auth'])

return redirect_to users_sign_in_path, notice: 'Failed to sign in!' unless user

sign_in(create_passwordless_session(user))

redirect_to Passwordless.config.success_redirect_path, status: :see_other
end

def failure
redirect_to users_sign_in_path, notice: 'Failed to sign in!'
end
end

This controller assumes that the User needs to exist, and if it doesn’t, it will fail the login.

The last thing is to add the method to the User model that will return the User to sign in:

# frozen_string_literal: true

class User < ApplicationRecord
passwordless_with :email

def self.from_omni_auth(auth)
find_by(email: auth.info.email)
end

end

Voila!

--

--

Henrik Hauge Bjørnskov

I build stuff at Relatel A/S, vivid traveller and gear junkie.