Giter VIP home page Giter VIP logo

omniauth's Introduction

OmniAuth: Standardized Multi-Provider Authentication

Gem Version Ruby TruffleRuby JRuby Code Climate Coverage Status

This is the documentation for the in-development branch of OmniAuth. You can find the documentation for the latest stable release here

An Introduction

OmniAuth is a library that standardizes multi-provider authentication for web applications. It was created to be powerful, flexible, and do as little as possible. Any developer can create strategies for OmniAuth that can authenticate users via disparate systems. OmniAuth strategies have been created for everything from Facebook to LDAP.

In order to use OmniAuth in your applications, you will need to leverage one or more strategies. These strategies are generally released individually as RubyGems, and you can see a community maintained list on the wiki for this project.

One strategy, called Developer, is included with OmniAuth and provides a completely insecure, non-production-usable strategy that directly prompts a user for authentication information and then passes it straight through. You can use it as a placeholder when you start development and easily swap in other strategies later.

Getting Started

Each OmniAuth strategy is a Rack Middleware. That means that you can use it the same way that you use any other Rack middleware. For example, to use the built-in Developer strategy in a Sinatra application you might do this:

require 'sinatra'
require 'omniauth'

class MyApplication < Sinatra::Base
  use Rack::Session::Cookie
  use OmniAuth::Strategies::Developer
end

Because OmniAuth is built for multi-provider authentication, you may want to leave room to run multiple strategies. For this, the built-in OmniAuth::Builder class gives you an easy way to specify multiple strategies. Note that there is no difference between the following code and using each strategy individually as middleware. This is an example that you might put into a Rails initializer at config/initializers/omniauth.rb:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :developer unless Rails.env.production?
  provider :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET']
end

You should look to the documentation for each provider you use for specific initialization requirements.

Integrating OmniAuth Into Your Application

OmniAuth is an extremely low-touch library. It is designed to be a black box that you can send your application's users into when you need authentication and then get information back. OmniAuth was intentionally built not to automatically associate with a User model or make assumptions about how many authentication methods you might want to use or what you might want to do with the data once a user has authenticated. This makes OmniAuth incredibly flexible. To use OmniAuth, you need only to redirect users to /auth/:provider, where :provider is the name of the strategy (for example, developer or twitter). From there, OmniAuth will take over and take the user through the necessary steps to authenticate them with the chosen strategy.

Once the user has authenticated, what do you do next? OmniAuth simply sets a special hash called the Authentication Hash on the Rack environment of a request to /auth/:provider/callback. This hash contains as much information about the user as OmniAuth was able to glean from the utilized strategy. You should set up an endpoint in your application that matches to the callback URL and then performs whatever steps are necessary for your application.

The omniauth.auth key in the environment hash provides an Authentication Hash which will contain information about the just authenticated user including a unique id, the strategy they just used for authentication, and personal details such as name and email address as available. For an in-depth description of what the authentication hash might contain, see the Auth Hash Schema wiki page.

Note that OmniAuth does not perform any actions beyond setting some environment information on the callback request. It is entirely up to you how you want to implement the particulars of your application's authentication flow.

rack_csrf

omniauth is not OOTB-compatible with rack_csrf. In order to do so, the following code needs to be added to the application bootstrapping code:

OmniAuth::AuthenticityTokenProtection.default_options(key: "csrf.token", authenticity_param: "_csrf")

Rails (without Devise)

To get started, add the following gems

Gemfile:

gem 'omniauth'
gem "omniauth-rails_csrf_protection"

Then insert OmniAuth as a middleware

config/initializers/omniauth.rb:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :developer if Rails.env.development?
end

Additional providers can be added here in the future. Next we wire it all up using routes, a controller and a login view.

config/routes.rb:

  get 'auth/:provider/callback', to: 'sessions#create'
  get '/login', to: 'sessions#new'

app/controllers/sessions_controller.rb:

class SessionsController < ApplicationController
  def new
    render :new
  end

  def create
    user_info = request.env['omniauth.auth']
    raise user_info # Your own session management should be placed here.
  end
end

app/views/sessions/new.html.erb:

<%= form_tag('/auth/developer', method: 'post', data: {turbo: false}) do %>
  <button type='submit'>Login with Developer</button>
<% end %>

Now if you visit /login and click the Login button, you should see the OmniAuth developer login screen. After submitting it, you are returned to your application at Sessions#create. The raise should now display all the Omniauth details you have available to integrate it into your own user management.

If you want out of the box usermanagement, you should consider using Omniauth through Devise. Please visit the Devise Github page for more information.

Rails API

The following middleware are (by default) included for session management in Rails applications. When using OmniAuth with a Rails API, you'll need to add one of these required middleware back in:

  • ActionDispatch::Session::CacheStore
  • ActionDispatch::Session::CookieStore
  • ActionDispatch::Session::MemCacheStore

The trick to adding these back in is that, by default, they are passed session_options when added (including the session key), so you can't just add a session_store.rb initializer, add use ActionDispatch::Session::CookieStore and have sessions functioning as normal.

To be clear: sessions may work, but your session options will be ignored (i.e. the session key will default to _session_id). Instead of the initializer, you'll have to set the relevant options somewhere before your middleware is built (like application.rb) and pass them to your preferred middleware, like this:

application.rb:

config.session_store :cookie_store, key: '_interslice_session'
config.middleware.use ActionDispatch::Cookies # Required for all session management
config.middleware.use ActionDispatch::Session::CookieStore, config.session_options

(Thanks @mltsy)

Logging

OmniAuth supports a configurable logger. By default, OmniAuth will log to STDOUT but you can configure this using OmniAuth.config.logger:

# Rails application example
OmniAuth.config.logger = Rails.logger

Origin Param

The origin url parameter is typically used to inform where a user came from and where, should you choose to use it, they'd want to return to. Omniauth supports the following settings which can be configured on a provider level:

Default:

provider :twitter, ENV['KEY'], ENV['SECRET']
POST /auth/twitter/?origin=[URL]
# If the `origin` parameter is blank, `omniauth.origin` is set to HTTP_REFERER

Using a differently named origin parameter:

provider :twitter, ENV['KEY'], ENV['SECRET'], origin_param: 'return_to'
POST /auth/twitter/?return_to=[URL]
# If the `return_to` parameter is blank, `omniauth.origin` is set to HTTP_REFERER

Disabled:

provider :twitter, ENV['KEY'], ENV['SECRET'], origin_param: false
POST /auth/twitter
# This means the origin should be handled by your own application. 
# Note that `omniauth.origin` will always be blank.

Resources

The OmniAuth Wiki has actively maintained in-depth documentation for OmniAuth. It should be your first stop if you are wondering about a more in-depth look at OmniAuth, how it works, and how to use it.

OmniAuth for Enterprise

Available as part of the Tidelift Subscription.

The maintainers of OmniAuth and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. Learn more.

Supported Ruby Versions

OmniAuth is tested under 2.5, 2.6, 2.7, 3.0, 3.1, 3.2, truffleruby, and JRuby.

Versioning

This library aims to adhere to Semantic Versioning 2.0.0. Violations of this scheme should be reported as bugs. Specifically, if a minor or patch version is released that breaks backward compatibility, that version should be immediately yanked and/or a new version should be immediately released that restores compatibility. Breaking changes to the public API will only be introduced with new major versions. As a result of this policy, you can (and should) specify a dependency on this gem using the Pessimistic Version Constraint with two digits of precision. For example:

spec.add_dependency 'omniauth', '~> 1.0'

License

Copyright (c) 2010-2017 Michael Bleigh and Intridea, Inc. See LICENSE for details.

omniauth's People

Contributors

achiurizo avatar bobbymcwho avatar boyvanamstel avatar chrispeterson avatar cromulus avatar estepnv avatar gacha avatar gogainda avatar he9qi avatar holman avatar jaigouk avatar jamesarosen avatar jamiew avatar jerryluk avatar kachick avatar leemartin avatar leshill avatar lexer avatar mbleigh avatar md5 avatar nschonni avatar pchilton avatar pupeno avatar quake avatar rainux avatar schneems avatar sferik avatar tmilewski avatar tomtaylor avatar twalpole avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

omniauth's Issues

License?

Could a license file be included with OmniAuth?

Session Restore Error with OpenID

If I at one point add the provider :open_id option and later remove it, I will get this error when visiting my application.

ActionDispatch::Session::SessionRestoreError

Session contains objects whose class definition isn't available.
Remember to require the classes for all objects kept in the session.
(Original exception: uninitialized constant OpenID [NameError])

Looks like it's storing an OpenID object directly in the session. Perhaps it can be stored as a hash or something more primitive so this isn't a problem?

Error installing omniauth

When I try to install the omniauth gem I get the following error:
ERROR: Error installing omniauth:
oa-basic requires restclient (>= 0, runtime)

This is even though I have verified that I do have the restclient gem installed.

OpenID auth_hash argument error

I'm using Omniauth 0.1.2 with Ruby 1.9.2 and Rails 3.0.0. When accessing /auth/open_id I get a form requesting me to fill in my OpenID. After logging in to my OpenID provider I'm redirected to /auth/open_id/callback with the following error.

ArgumentError (wrong number of arguments (0 for 1)):
oa-openid (0.1.2) lib/omniauth/strategies/open_id.rb:88:in `auth_hash'
oa-core (0.1.2) lib/omniauth/strategy.rb:42:in `callback_phase'
oa-openid (0.1.2) lib/omniauth/strategies/open_id.rb:82:in `callback_phase'
oa-core (0.1.2) lib/omniauth/strategy.rb:27:in `call!'
...

Looking into it, it appears the OpenID strategy overrides the auth_hash method and adds an argument to it. It looks like this argument isn't being passed in the callback_phase method.

Maybe pass in the response arg some other way so all strategies behave similarly and don't require different arguments?

Problem with TripIt

Not a whole lot of details, just this error message and a few references to Rails middleware rescue templates:

invalid value for Integer(): ":"

Rails 3.0.1, Ruby 1.9.2

Gem push omniauth 0.0.4

I have been getting issues installing 0.0.3 successfully. The recent commits seem to fix some of these issues, it would be nice if we could get this gem pushed out soon? thanks.

Configure paths for actions

Ideally it would be nice if you could configure separate paths for different actions.
Setting your own custom authorize/callback and failure paths could make it easier to integrate into existing applications. This mainly applies for failures though.

Omniauth still using an older version of faraday?

Trying to install omniauth from GIT and I get through bundle install:

Bundler could not find compatible versions for gem "faraday":
In Gemfile:
omniauth depends on
faraday (~> 0.4.1)

twitter depends on
  faraday (0.5.1)

It seems there it is incompatible with the Twitter gem. Why is Omniauth still using an older version of Faraday? Is there any reason for this?

OpenID strategy name option deletion causes route to change

In oa-openid-0.1.4, the OpenID Strategy instantiation deletes :name from the options hash (lib/omniauth/strategies OpenID#initialize(): line 27). From the 2nd time on, the default name is used as opposed to the user-specified name. This causes the auth/#{name} path to change after the first time it is used. For example, if I set :name => :google, when I point the browser to auth/google, everything works fine. If I refresh the same url, the route is not recognized. But the default auth/google_apps works this time. In v0.1.3, the :name option is not deleted. Is there a reason the :name option is deleted?

there should be a way to override the facebook scope

Passing a :scope to the provider method does not actually override the default scope being passed. I had to monkeypatch around it.

module OmniAuth
  module Strategies
    class Facebook
      def request_phase(options = {})
        options[:scope] ||= "email,offline_access,publish_stream"
        super(options)
      end
    end
  end
end

omniauth/strategies/oauth.rb: in request_phase, line 17 fail in a Rails 3 app

I just started to migrate a Rails 3 app to OmniAuth from Devise. I would like to use Twitter and Facebook as an authentication provider.

If I navigate to /auth/twitter my app fail. The error message is this:
omniauth/strategies/oauth.rb: in request_phase, line 17

My config.ru file:
require ::File.expand_path('../config/environment', FILE)
use OmniAuth::Builder do
provider :twitter, 'xy', 'xy'
provider :facebook, '', ''
end

I test it on localhost, I know it won't fire the callback, but I think it should redirect me to Twitter without any hassle. What can go wrong?

Thanks!

OmniAuth should update its Rack dependency

Rack 1.2 is out. OmniAuth currently depends on rack ~> 1.1, which excludes 1.2. Complex dependency requirements like ">= 1.1, < 2" aren't allowed, so what should we use? ">= 1.1" will work for now, but might fail if Rack breaks something we rely on in a later version.

OpenID identifier form should have OpenID logo as background image

Use the following, from Railscasts 68

/* embeds the openid image in the text field */
input#openid_url {
  background: url(http://openid.net/login-bg.gif) no-repeat;
  background-color: #fff;
  background-position: 0 50%;
  color: # 000; /* there shouldn't be a space before the 0, but GitHub's parser tries to turn it into an issue link */
  padding-left: 18px;
}

Add ActiveModel support

  • OmniAuth::ActiveModel::LoadUser - if the 'auth' Hash exists, load a User (class configurable) via Credential.where(:provider => provider, :uid => uid).user.
  • OmniAuth::ActiveModel::AddCredentialToUser - if signed in and the 'auth' Hash exists, add the Credential (class configurable) to the signed in User's #credentials.
  • OmniAuth::ActiveModel::CreateUserFromCredential - if not signed in and the 'auth' Hash exists and no corresponding User is found, create a new one from the Credential.
  • OmniAuth::ActiveModel::DoItForMe - all three of the above, in order

Strategy#initialize should yield a block on initialization

Something along these lines is ok:

def initialize(app, name, *args)
  @app = app
  @name = name.to_sym
  yield self if block_given?
end

Michael mentioned an interested on having blocks being executed on each request. We can likely achieve that using a small builder:

use Twitter do |strategy|
  # This is Devise use case. Read/write a value on initialization.
  strategy.client = Faraday::Connection.new

  # This is on request use case.
  strategy.on_request { |env| # do something }
end

on_request would simply be a method in the strategy that stores the lambda.

Request-URI Too Large error with OpenID

Using Omniauth 0.1.2 with Ruby 1.9.2 and Rails 3, when I access /auth/open_id and include "http://" as part of my open id identifier (like "http://ryanbates.myopenid.com"), WEBrick will raise a WEBrick::HTTPStatus::RequestURITooLarge error. The URL includes /auth/open_id/callback with many parameters.

I don't know if this is just a limitation of WEBrick, but it would be nice if this gem generated shorter urls so this wasn't a problem.

request_phase should be run after the application

Right now the request_phase completely ignores the application. Numerous people have requested the ability for runtime configuration of providers, and there's no way to do this when the app isn't involved in the mix. I'm proposing calling the app and handling a few different things, including runtime configuration or optionally preventing the authentication flow through some means (for instance, if an app doesn't want logged in users to try to log in again).

Need some more thought on implementation, but this is a definite win for making it more flexible.

Oauth strategies should check if params[:error] was not given to the callback url

The current oauth strategy always assume a code was returned back from the client, which is not always true. According to oauth specs, Omniauth should check if params[:error] was sent as well. You may also want to check for params[:error_reason], which is not in the specs but is what facebook returns currently.

Here is some excerpt from Devise Oauth2:

http://github.com/plataformatec/devise/blob/master/lib/devise/oauth/internal_helpers.rb#L86

Google queried on all OpenID requests

The ruby-openid-apps-discovery adds Google apps-specific functionality to the OpenID discovery process. Unfortunately it adds it first, so all OpenID requests query Google first, then continue through the normal discovery process, regardless of the host of a given domain.

If "require 'gapps_openid'" is moved to strategy/google_apps the Google App strategy won't happen when the OmniAuth's Google App strategy isn't used. However, once it is required, it pollutes all OpenID discovery, not just Google Apps.

Here's an example of a patch that tries regular discovery first, and the Google-specific discovery second. The idea is that if a uri is hosting an OpenIDs, Google shouldn't have the opportunity to override that. It looks like it should work, but I don't have a Google Apps account to verify.
http://github.com/samsm/omniauth/tree/less-obtrusive-gapps

Use omniauth namespace in the Rack env, not rack

According to the Rack spec:

The prefix rack. is reserved for use with the Rack core distribution and other accepted specifications and must not be used otherwise.

Omniauth should use its own namespace (proposal: omniauth.auth rather than rack.auth).

Wrapper plugin for use in Ruby on Rails

I try to use this gem in Rails, but I don't know which is the best way to integrate. Maybe a wrapper plugin for Rails will be nice. I read in the roadmap that there's a plan to build a Rails3 engine, but I think that it'll be great to have support for Rails 2.3.x.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.