Skip to content

Create an OmniAuth strategy for your provider

Giles edited this page Dec 2, 2019 · 1 revision

To create a strategy for your provider you'll first need an API endpoint that will return the resource owner's credentials. This will be part of your API and you'll have to protect it with doorkeeper:

# app/controllers/api/v1/credentials_controller.rb
module Api::V1
  class CredentialsController < ApiController
    before_action :doorkeeper_authorize!
    respond_to     :json

    def me
      respond_with current_resource_owner
    end
  end
end

The current_resource_owner method returns the user that is the owner of the current access token. You may want to define this in your ApiController to make this available across your API controllers:

module Api::V1
  class ApiController < ::ApplicationController
    private
    def current_resource_owner
      User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
    end
  end
end

And in your routes:

# config/routes.rb
namespace :api do
  namespace :v1 do
    # another api routes
    get '/me' => "credentials#me"
  end
end

This example was extracted from our live demo (source code)

OmniAuth Strategy

If you want to provide your API users an OmniAuth strategy, you'll need this snippet:

require 'omniauth-oauth2'

module OmniAuth
  module Strategies
    class Doorkeeper < OmniAuth::Strategies::OAuth2
      # change the class name and the :name option to match your application name
      option :name, :doorkeeper

      option :client_options, {
        :site => "http://my_awesome_application.com",
        :authorize_url => "/oauth/authorize"
      }

      uid { raw_info["id"] }

      info do
        {
          :email => raw_info["email"]
          # and anything else you want to return to your API consumers
        }
      end

      def raw_info
        @raw_info ||= access_token.get('/api/v1/me.json').parsed
      end

      # https://github.com/intridea/omniauth-oauth2/issues/81
      def callback_url
        full_host + script_name + callback_path
      end
    end
  end
end

This is an example of strategy that is based on doorkeeper defaults. Few considerations:

  1. The :client_options are default for doorkeeper engine. You'll only need to change the site parameter.
  2. You may want to return more data in the info block. It's a common practice among OAuth providers to have a "credentials" endpoint that returns the current user's info. Check out facebook and twitter strategies for example.

Devise and OmniAuth

The snippet above is pretty much everything you need to do to release a OmniAuth strategy gem for your provider. With that, users which have devise in their clients can easily integrate their apps with your provider:

Devise.setup do |config|
  config.omniauth :doorkeeper, ENV['DOORKEEPER_APP_ID'], ENV['DOORKEEPER_APP_SECRET']
end
Clone this wiki locally