- Server Application (Devise + Doorkeeper) - oauth provider
- Client Application (Ominauth-oauth2) - oauth client
Setup doorkeeper client Application with Rails 8
use omniauth with custom omniauth strategy to authenticate via doorkeeper server
- Gemfile
gem 'rails', '8.0.2.1'
gem 'devise', '4.8.1'
gem "omniauth", "1.9.1"
gem "omniauth-oauth2", "~> 1.7"
gem "rack", "~> 2.0"
Notes.
-
latest version ‘2.1.0’ of gem
ominiauthdoesn’t work well together with doorkeeper. -
have to use rack 2.x instead of 3.x because of requirements of
omniauthgem -
routes.rb
devise_for :users, controllers: {
sessions: 'users/sessions',
registrations: 'users/registrations',
omniauth_callbacks: 'users/omniauth_callbacks'
} do
delete 'sign_out', to: 'devise/sessions#destroy', as: :destroy_user_session
end
- .env
have env vars
AUTH_APP_URL="http://localhost:3099"
DOORKEEPER_APP_ID=xxx
DOORKEEPER_APP_SECRET=yyy
AUTH_APP_URL - url of doorkeeper server app
- config/initializers/devise.rb
require 'omniauth_strategy_doorkeeper'
Devise.setup do |config|
..
config.omniauth :doorkeeper,
ENV['DOORKEEPER_APP_ID'],
ENV['DOORKEEPER_APP_SECRET'],
# scope: 'read',
strategy_class: ::OmniauthStrategyDoorkeeper,
fields: ['id', 'email', 'first_name', 'last_name']
- app/lib/omniauth_strategy_doorkeeper.rb
class OmniauthStrategyDoorkeeper < ::OmniAuth::Strategies::OAuth2
option :name, :doorkeeper
option :client_options,
site: ENV["AUTH_APP_URL"],
authorize_path: "#{ENV["AUTH_APP_URL"]}/oauth/authorize"
uid do
raw_info["id"]
end
info do
{
email: raw_info["email"],
first_name: raw_info["first_name"],
last_name: raw_info["last_name"],
locale: raw_info["locale"],
}
end
def raw_info
@raw_info ||= access_token.get("/api/me").parsed
end
end