Rodauth feature that offers login and registration via multiple external providers using OmniAuth, together with the persistence of external identities.
Add the gem to your project:
$ bundle add rodauth-omniauth
You'll first need to create the table for storing external identities:
Sequel.migration do
change do
create_table :account_identities do
primary_key :id
foreign_key :account_id, :accounts
String :provider, null: false
String :uid, null: false
unique [:provider, :uid]
end
end
end
class CreateAccountIdentities < ActiveRecord::Migration
def change
create_table :account_identities do |t|
t.references :account, null: false, foreign_key: { on_delete: :cascade }
t.string :provider, null: false
t.string :uid, null: false
t.index [:provider, :uid], unique: true
end
end
end
Then enable the omniauth
feature and register providers in your Rodauth configuration:
$ bundle add omniauth-facebook omniauth-twitter, omniauth-google-oauth2
plugin :rodauth do
enable :omniauth
omniauth_provider :facebook, ENV["FACEBOOK_APP_ID"], ENV["FACEBOOK_APP_SECRET"], scope: "email"
omniauth_provider :twitter, ENV["TWITTER_API_KEY"], ENV["TWITTER_API_SECRET"]
omniauth_provider :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"], name: :google
end
It is important to note that rodauth-omniauth
requires OmniAuth 2.x, and as such, is only compatible with omniauth gems that use the same.
You can now add authentication links to your login form:
<!-- app/views/rodauth/_login_form_footer.html.erb -->
<!-- ... -->
<li><%= button_to "Login via Facebook", rodauth.omniauth_request_path(:facebook), method: :post, data: { turbo: false }, class: "btn btn-link p-0" %></li>
<li><%= button_to "Login via Twitter", rodauth.omniauth_request_path(:twitter), method: :post, data: { turbo: false }, class: "btn btn-link p-0" %></li>
<li><%= button_to "Login via Google", rodauth.omniauth_request_path(:google), method: :post, data: { turbo: false }, class: "btn btn-link p-0" %></li>
<!-- ... -->
Assuming you configured the providers correctly, you should now be able to authenticate via an external provider. The omniauth
feature handles the callback request, automatically creating new identities and verified accounts from those identities as needed.
Account.all
#=> [#<Account @values={ id: 123, status_id: 2, email: "[email protected]" }>]
Account::Identity.all
#=> [#<Account::Identity @values={ id: 456, account_id: 123, provider: "facebook", uid: "984346198764" }>,
# #<Account::Identity @values={ id: 789, account_id: 123, provider: "google", uid: "5871623487134"}>]
The example above assumes you're using rodauth-model (automatically setup with rodauth-rails), which will define Account::Identity
model for the account_identities
table, along with the identities
association on the Account
model.
account = Account.first
account.identities #=> [#<Account::Identity ...>, ...]
Currently, provider login is required to return the user's email address, and account creation is assumed not to require additional fields that need to be entered manually. There is currently also no built-in functionality for connecting/removing external identities when signed in. Both features are planned for future versions.
After provider login, you can perform custom logic at the start of the callback request:
before_omniauth_callback_route do
omniauth_provider #=> :google
end
If the external identity doesn't already exist, and there is an account with email matching the identity's, the new identity will be assigned to that account. You can change how existing accounts are searched after provider login:
account_from_omniauth do
account_table_ds.first(email: omniauth_email) # roughly the default implementation
end
# or
account_from_omniauth {} # disable finding existing accounts for new identities
If the account associated to the external identity exists and is unverified (e.g. it was created through normal registration), the callback phase will automatically verify the account and login, assuming the verify_account
feature is enabled and external email is the same.
If you wish to disallow OmniAuth login into unverified accounts, set the following:
omniauth_verify_account? false
You can change the default error flash and redirect location in this case:
omniauth_login_unverified_account_error_flash "The account matching the external identity is currently awaiting verification"
omniauth_login_failure_redirect { require_login_redirect }
Accounts created via external login are automatically verified, because it's assumed your email address was verified by the external provider. If you want to use extra user information for account creation, you can do so via hooks:
before_omniauth_create_account { account[:name] = omniauth_name }
# or
after_omniauth_create_account do
Profile.create(account_id: account_id, bio: omniauth_info["description"], image_url: omniauth_info["image"])
end
When the account is closed, its external identities are automatically deleted from the database.
You can also store extra data on the external identities. For example, we could override the update hash to store info
, credentials
, and extra
data from the auth hash into separate columns:
alter_table :account_identities do
add_column :info, :json, default: "{}"
add_column :credentials, :json, default: "{}"
add_column :extra, :json, default: "{}"
end
# this data will be refreshed on each login
omniauth_identity_update_hash do
{
info: omniauth_info.to_json,
credentials: omniauth_credentials.to_json,
extra: omniauth_extra.to_json,
}
end
With this configuration, the identity record will be automatically synced with most recent state on each provider login. If you would like to only save provider data when the identity is created, you can override the insert hash instead:
# this data will be stored only on first login
omniauth_identity_insert_hash do
super().merge(
info: omniauth_info.to_json,
credentials: omniauth_credentials.to_json,
extra: omniauth_extra.to_json,
}
end
You can change the table name or any of the column names:
omniauth_identities_table :account_identities
omniauth_identities_id_column :id
omniauth_identities_account_id_column :account_id
omniauth_identities_provider_column :provider
omniauth_identities_uid_column :uid
The omniauth
feature builds on top of the omniauth_base
feature, which sets up OmniAuth and routes its requests, but has no interaction with the database. So, if you would prefer to handle external logins differently, you can load just the omniauth_base
feature, and implement your own callback phase.
plugin :rodauth do
enable :omniauth_base
omniauth_provider :github, ENV["GITHUB_CLIENT_ID"], ENV["GITHUB_CLIENT_SECRET"], scope: "user"
omniauth_provider :apple, ENV["APPLE_CLIENT_ID"], ENV["APPLE_CLIENT_SECRET"], scope: "email name"
end
route do |r|
r.rodauth # routes Rodauth and OmniAuth requests
r.get "auth", String, "callback" do
# ... handle callback request ...
end
end
There are various helper methods available for reading OmniAuth data:
# retrieving the auth hash:
rodauth.omniauth_auth #=> { "provider" => "twitter", "uid" => "49823724", "info" => { "email" => "[email protected]", "name" => "John Smith", ... }, ... }
rodauth.omniauth_provider #=> "twitter"
rodauth.omniauth_uid #=> "49823724"
rodauth.omniauth_info #=> { "email" => "[email protected]", "name" => "John Smith", ... }
rodauth.omniauth_email #=> "[email protected]"
rodauth.omniauth_name #=> "John Smith"
rodauth.omniauth_credentials #=> returns "credentials" value from auth hash
rodauth.omniauth_extra #=> returns "extra" value from auth hash
# retrieving additional information:
rodauth.omniauth_strategy #=> #<OmniAuth::Strategies::Twitter ...>
rodauth.omniauth_params # returns GET params from request phase
rodauth.omniauth_origin # returns origin from request phase (usually referrer)
# retrieving error information in case of a login failure
rodauth.omniauth_error # returns the exception object
rodauth.omniauth_error_type # returns the error type symbol (strategy-specific)
rodauth.omniauth_error_strategy # returns the strategy for which the error occured
URL helpers are provided as well:
rodauth.prefix #=> "/user"
rodauth.omniauth_prefix #=> "/auth"
rodauth.omniauth_request_route(:facebook) #=> "auth/facebook"
rodauth.omniauth_request_path(:facebook) #=> "/user/auth/facebook"
rodauth.omniauth_request_url(:facebook) #=> "https://example.com/user/auth/facebook"
rodauth.omniauth_callback_route(:facebook) #=> "auth/facebook/callback"
rodauth.omniauth_callback_path(:facebook) #=> "/user/auth/facebook/callback"
rodauth.omniauth_callback_url(:facebook) #=> "https://example.com/user/auth/facebook/callback"
The prefix for the OmniAuth app can be changed:
omniauth_prefix "/external"
OmniAuth configuration has global hooks for various phases, which get called with the Rack env hash. Here you can use corresponding Rodauth configuration methods, which are executed in Rodauth context:
omniauth_setup { ... }
omniauth_request_validation_phase { ... }
omniauth_before_request_phase { ... }
omniauth_before_callback_phase { ... }
omniauth_on_failure { ... }
You can use the omniauth_strategy
helper method to differentiate between strategies:
omniauth_setup do
if omniauth_strategy.name == :github
omniauth_strategy.options[:foo] = "bar"
end
end
The default reaction to login failure is to redirect to the root page with an error flash message. You can change the configuration:
omniauth_failure_error_flash "There was an error logging in with the external provider"
omniauth_failure_redirect { default_redirect }
omniauth_failure_error_status 500 # for JSON API
Or provide your own implementation:
omniauth_on_failure do
case omniauth_error_type
when :no_authorization_code then # ...
when :uknown_signature_algorithm then # ...
else # ...
end
end
The default request validation phase uses Rodauth's configured CSRF protection, so there is no need for external gems such as omniauth-rails_csrf_protection
.
The registered providers are inherited between Rodauth auth classes, so you can have fine-grained configuration for different account types.
class RodauthBase < Rodauth::Auth
configure do
enable :omniauth_base
omniauth_provider :google_oauth2, ...
end
end
class RodauthMain < RodauthBase
configure do
omniauth_provider :facebook, ...
end
end
class RodauthAdmin < RodauthBase
configure do
omniauth_provider :twitter, ...
omniauth_provider :github, ...
end
end
class RodauthApp < Roda
plugin :rodauth, auth_class: RodauthMain
plugin :rodauth, auth_class: RodauthAdmin, name: :admin
end
rodauth.omniauth_providers #=> [:google_oauth2, :facebook]
rodauth(:admin).omniauth_providers #=> [:google_oauth2, :twitter, :github]
JSON requests are supported for request and callback phases. The request phase endpoint will return the authorize URL:
POST /auth/github
Accept: application/json
Content-Type: application/json
200 OK
Content-Type: application/json
{ "authorize_url": "https://github.com/login/oauth/authorize?..." }
When you redirect the user to the authorize URL, and they authorize the OAuth app, the callback endpoint they're redirected to will contain query parameters that need to be included in the callback request to the backend.
GET /auth/github/callback?code=...&state=...
Accept: application/json
Content-Type: application/json
200 OK
Content-Type: application/json
{ "success": "You have been logged in" }
If there was an OmniAuth failure, the error type will be included in the response:
500 Internal Server Error
Content-Type: application/json
{ "error_type": "some_error", "error": "There was an error logging in with the external provider" }
In this flow, you'll need to configure the callback URL on the OAuth app to point to the frontend app. In the OmniAuth strategy, you'll need to configure the same redirect URL for OAuth requests, but keep the backend callback endpoint. For strategies based on omniauth-oauth2, you can achieve this as follows:
omniauth_provider :github, ENV["GITHUB_CLIENT_ID"], ENV["GITHUB_CLIENT_SECRET"],
authorize_params: { redirect_uri: "https://frontend.example.com/github/callback" },
token_params: { redirect_uri: "https://frontend.example.com/github/callback" }
You can change authorize URL and error type keys:
omniauth_authorize_url_key "authorize_url"
omniauth_error_type_key "error_type"
JWT requests are supported for the request and callback phases. OmniAuth data will be stored in the JWT token during the request phase, and restored during the callback phase, as long as the updated JWT token is passed.
Run tests with Rake:
$ bundle exec rake test
The implementation of this gem was inspired by this OmniAuth guide.
The gem is available as open source under the terms of the MIT License.
Everyone interacting in the rodauth-omniauth project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.