# Login to Discourse with custom Oauth2 provider

**URL:** <https://meta.discourse.org/t/login-to-discourse-with-custom-oauth2-provider/14717>\
**Category:** Feature\
**Tags:** oauth2, completed\
**Created:** [2014 年4 月 12 日 12:55 UTC](https://meta.discourse.org/t/login-to-discourse-with-custom-oauth2-provider/14717 "2014-04-12T12:55:42Z")\
**Posts on this page:** 1\
**Showing post:** 3

<div class="post-metadata">

作者： ![radq](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/radq/32/104329_2.png) [@radq](https://meta.discourse.org/u/radq)\
发布日期： [2014 年4 月 12 日 15:34 UTC](https://meta.discourse.org/t/login-to-discourse-with-custom-oauth2-provider/14717/3 "2014-04-12T15:34:28Z")

</div>

Discourse has support for custom [OAuth2 authentication](https://github.com/discourse/discourse/blob/master/lib/auth/oauth2_authenticator.rb) built in, here’s an example of how you can add a custom auth mechanism using OAuth2 via a plugin:

```ruby
require 'auth/oauth2_authenticator'
require 'omniauth-oauth2'

class HummingbirdAuthenticator < ::Auth::OAuth2Authenticator

  CLIENT_ID = '...'
  CLIENT_SECRET = '...'

  def register_middleware(omniauth)
    omniauth.provider :hummingbird, CLIENT_ID, CLIENT_SECRET
  end
end

class OmniAuth::Strategies::Hummingbird < OmniAuth::Strategies::OAuth2
  # Give your strategy a name.
  option :name, "hummingbird"

  # This is where you pass the options you would pass when
  # initializing your consumer from the OAuth gem.
  option :client_options, site: 'http://hummingbird.me'

  # These are called after authentication has succeeded. If
  # possible, you should try to set the UID without making
  # additional calls (if the user id is returned with the token
  # or as a URI parameter). This may not be possible with all
  # providers.
  uid { raw_info['id'].to_s }

  info do
    {
      :name => raw_info['name'],
      :email => raw_info['email']
    }
  end

  extra do
    {
      'raw_info' => raw_info
    }
  end

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

auth_provider :title => 'Sign in with Hummingbird account',
    :message => 'Log in using your Hummingbird account. (Make sure your popup blocker is disabled.)',
    :frame_width => 920,
    :frame_height => 800,
    :authenticator => HummingbirdAuthenticator.new('hummingbird', trusted: true,
      auto_create_account: true)

```

---

_[View the full topic](https://meta.discourse.org/t/login-to-discourse-with-custom-oauth2-provider/14717)._
