Giter VIP home page Giter VIP logo

omniauth-instagram'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-instagram's People

Contributors

bilalbudhani avatar bobbymcwho avatar gaizka avatar imack avatar ksylvest avatar rdsoze avatar ropiku avatar sathishachilles avatar siong1987 avatar tmilewski avatar ys 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

omniauth-instagram's Issues

https in callback url

Hi,

i have succesfully integrated the gem. The only small issue is that the callback url send to instagram is http, even when the site is delivered in https only.
Is it possible to generate a https callback uri that is send to instagram?

TIA
Steffen

Getting access_denied | The user denies your request while I accept the request

Hey guys,

I am currently trying to set a OAuth connexion via Instagram and I found this gem. I successfully plugged it for Facebook, linkedin and Google + but I am currently struggling with Instagram connexion.

The reason is that I get this error when I click on "Authorize" on the Instagram connexion page

ERROR -- omniauth: (instagram) Authentication failure! user_denied: OmniAuth::Strategies::OAuth2::CallbackError, access_denied | The user denied your request.

I hence get redirect to my failure method:

Parameters: {"error_reason"=>"user_denied", "error"=>"access_denied", "error_description"=>"The user denied your request.", "state"=>"d54f932ff4bada3abd784e39886b96d324f753929d410d97"}

Here is how I configured my provider in my devise.rb file :

config.omniauth :instagram, instagram_id, instagram_secret, {
    scope: "basic"
  }

Nothing fancy going on here.
Here are the version of the gems that I am using :

omniauth-instagram (1.3.0)
      omniauth (~> 1)
      omniauth-oauth2 (~> 1)

I tried looking it up but I couldn't find any related solutions.

Thanks for your feedback

Forcing a New Login

Is there a way to force a new login like Twitter allows by going something like:

  :authorize_params => {
    :force_login => 'true',
    :lang => 'pt'
  }

How do I get a successful callback?

Navigating to /auth/instagram/callback#access_token=********************* doesnt seem to do the trick.

I get the following error:

OAuth2::Error at /auth/instagram/callback:
{"code": 400, "error_type": "OAuthException", "error_message": "You must provide a code"}

Any clue how to solve this?

Can I require authorization/login each time?

I'm needing to force authorization/login each time a user tries to access my client, doesn't matter if they already did it or not. Is this possible? I've search everywhere and looked at other API's ways of doing it but it didn't work for Instagram.

client_id is not setting in URL for Instagram, when deployed to Heroku.

Hello,

I have created the client in instagram developer, and using the client_id and secret in env file in the local application. It works perfectly fine. But when I deployed to Heroku, and created the new keys and redirect_url it is not setting client_id in URL, when redirecting to auth page.

PS: I have even created the OAuth from Heroku and added it to my app, still no luck.
https://github.com/heroku/heroku-cli-oauth

Please somebody help me.

Getting "Invalid redirect_uri" in development

Hi,

I am working on a new application utilizing IG's OAuth, and keep running in to this error when hitting IG's authentication api in development:

{
  "error_type": "OAuthException",
  "code": 400,
  "error_message": "Invalid redirect_uri"
}

I tried pushing the code to Heroku and everything works, so I know my setup on FB developer console should be fine.

I am assuming it's an https issue, and is attempting to use ngrok as work around.

Is there a better way to work with IG's authentication in development environment?

Thanks

Is this strategy still valid?

With instagram api becoming a part of facebook, is this strategy still valid or should I use facebook one (or write a custom one to access instagram data through facebook api)?

It is still trying to authenticate through old instagram api, but I think that this is only before they disable it?

Are there plans to allow this gem to use new api?

needs an update on omniauth dependency

currently it is dependent on omniauth version ~1.0 but the omniauth version 1.9.1 has reported high severity CVE and we need to update the omniauth version to ~2.0

Access Token

I am having trouble accessing the access token that is required on all api calls to get any data. The credentials['token'] does not work for me. Any insights on where in the maybe the request.env is would be? I can get the token through postman using https://api.instagram.com/oauth/authorize/?client_id=#{ENV['INSTAGRAM_ID']}&redirect_uri=REDIRECT_URI&response_type=token but it comes back in the cookies. All of the documentation that I see says to just get it the once. But wouldn't it expire?

EDIT: Sorry to have wasted time. I got it to work, haha.

client_id not set in url

I am authenticating using OmniAuth with both Twitter and Instagram. Twitter is working well.

When I start the authentication process with the /auth/instagram request, OmniAuth is not including the client_id in the authorization header.

I have initialized OmniAuth as:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :twitter, ENV.fetch('TWITTER_CONSUMER_KEY'), ENV.fetch('TWITTER_CONSUMER_SECRET')
  provider :instagram, ENV.fetch('INSTAGRAM_CLIENT_ID'), ENV.fetch('INSTAGRAM_CLIENT_SECRET')
end

When I send the /auth/instagram request, it returns:

{"code": 400, "error_type": "OAuthException", 
 "error_message": "You must include a valid client_id, response_type, and redirect_uri parameters"}

and shows the request uri without my client_id:

https://www.instagram.com/oauth/authorize?client_id=&redirect_uri=http://demo.herokuapp.com/auth/instagram/callback&response_type=code&scope=basic&state=952ced9482ccf34faf3e09cffd40f59548f3c5a539499723

Authentication failure on callback (crsf_detected)

I'm using:

    omniauth-instagram (1.0.2)
      omniauth (~> 1)
      omniauth-oauth2 (~> 1)
    omniauth-oauth2 (1.3.1)
      oauth2 (~> 1.0)
      omniauth (~> 1.2)

ERROR -- omniauth: (instagram) Authentication failure! csrf_detected: OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected

I don't know if this is helpful but found that this issue happens when you send along state and on callback it doesn't match.

And this is my callback url - Started
GET "/auth/instagram/callback?code=xxxxxxxxx&state=yyyyyyyy"

And my omniauth initializer setup is pretty vanilla too:

provider :instagram, OauthSecrets.instagram.client_id, OauthSecrets.instagram.client_secret

I assume this setup sends a state along? I know it's optiona but would be surprised if we're not doing this already?

Anyways, please let me know if you have any suggestions?

Thanks :)

Instructions on to setup omniauth for Instagram

I'm having a hard time setting this thing up. Maybe I'm doing something wrong or possibly missing a step. I'm new to rails so I appreciate any help.

  1. First I added gem 'omniauth-instagram', '~> 1.0.1' to my gem file
  2. Run bundle install inside terminal
  3. Add
use OmniAuth::Builder do
  provider :instagram, ENV['INSTAGRAM_ID'], ENV['INSTAGRAM_SECRET']
end

to config/initializers/omniauth.rb file
4. To test it out, I added <%= link_to "Sign in with Instagram", "/auth/instagram" %> inside my views.

I keep getting an error saying that route does not exist. (/auth/instagram)

Please help.

Working with omniauth-oauth2 1.1.0

When omniauth-oauth2 upgraded to 1.1.0 (from 1.0.3 previously) the omniauth-instagram couldn't process the callback url properly and would just give a OmniAuth::Strategies::OAuth2::CallbackError.


A quick work around:
update your gem file to give the specific version of omniauth-oauth2
gem 'omniauth-oauth2', '1.0.3'

If you use omniauth-facebook you'll need to specify it's version as well because the latest version of omniauth-facebook works with omniauth-oauth2 1.1.0 and not 1.0.3. So update your omniauth-facebook gem line to:
gem 'omniauth-facebook', '1.4.0'

run 'bundle update omniauth-oauth2'

Scope

Is there anyway that we can specify the scope of the authentication?

Thanks

Possibility of cutting new release?

Hi folks - would it be possible to cut a release to ruby gems? A commit merged recently contains an update of underlying dependencies and it would be of assistance if this could be published as such.

I appreciate the effort and your time : )

Instagram returns user_id, not id

I get this error undefined method [] for nil:NilClass when redirecting from instagram.
The error comes from omniauth-instagram (1.3.0) lib/omniauth/strategies/instagram.rb:22

I traced the error and figured out instagram does not return user field. It returns user_id, so instagram.rb:50 returns nil.

I saw there was an attempt to fix this - #42, but for some reason that PR was closed.

Is this going to be fixed soon? The gem does not seem to be usable now.

"Redirect URI doesn't match original redirect URI" error

Hi,

I've set up an Instagram app/client and Valid redirect URIs for my instagram app is like the following:

http://127.0.0.1.xip.io:3000/dashboard/omni/auth/instagram/callback

I've started to get Redirect URI doesn't match original redirect URI error.

Here is the backtrace:

I, [2015-11-27T13:34:10.883170 #10189]  INFO -- omniauth: (instagram) Callback phase initiated.
[httplog] Connecting: api.instagram.com:443
[httplog] Sending: POST http://api.instagram.com:443/oauth/access_token
[httplog] Data: client_id=11111&client_secret=22222&code=XXXXX&grant_type=authorization_code&redirect_uri=http://127.0.0.1.xip.io:3000/dashboard/omni/auth/instagram/callback?code=XXXXX&state=33333
[httplog] Status: 400
[httplog] Benchmark: 0.20239810000020952 seconds
[httplog] Response:
{"code": 400, "error_type": "OAuthException", "error_message": "Redirect URI doesn't match original redirect URI"}
E, [2015-11-27T13:34:11.487103 #10189] ERROR -- omniauth: (instagram) Authentication failure! invalid_credentials: OAuth2::Error, : 
{"code": 400, "error_type": "OAuthException", "error_message": "Redirect URI doesn't match original redirect URI"}

After digging around, I've noticed that if I remove query string from redirect_uri which is ?code=XXXXX&state=33333, it works like a charm. However, according to Instagram API Documentation(http://instagram.com/developer/authentication/) it is possible to use query parameters.

In order to remove query string from redirect_uri, I had to add the following method to omniauth-instagram-1.0.1/lib/omniauth/strategies/instagram.rb file:

def query_string
  ''
end

But, I'm not sure if this is the best solution. Is this a bug or is there a problem with my settings? This gem used to work before.

Thanks.

-Ozgun.

How to get a client?

Hi!

Sorry for a stupid question,
previously I used omniauth-twtter and passed configurations like this:

client = Twitter::REST::Client.new do |config|
config.consumer_key = "YOUR_CONSUMER_KEY"
config.consumer_secret = "YOUR_CONSUMER_SECRET"
config.access_token = "YOUR_ACCESS_TOKEN"
config.access_token_secret = "YOUR_ACCESS_SECRET"
end

and then I used it like client.user("gem")

How can I get the same thing with omniauth-instagram?

Thanks!

How to add Scope params

I'm using Omniauth with Devise. It's not documented how to specify your scopes, and it does not appear to follow the convention used by facebook, github and others. So if it helps anyone, here's how you'd specify your desired permissions:

config.omniauth :instagram, XXX, YYY, scope: %w(basic public_content follower_list)

The scope expects an array, or something that can be cast to an array.
Had me stumped for a moment till I dug through source.

Documentation Sucks

Not sure if it's outta date or what, but it covers absolutely nothing. Instagram API is super problematic and maybe not necessarily due to this library.

Is Instagram API Authentication broken?

When trying to authenticate to Instagram, I am receiving a html response: Page Not Found (This page could not be loaded. If you have cookies disabled in your browser, or you are browsing in Private Mode, please try enabling cookies or turning off Private Mode, and then retrying your action).

Anybody else facing this problem?

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.