Git Product home page Git Product logo

omniauth-google-oauth2's Introduction

Gem Version

OmniAuth Google OAuth2 Strategy

Strategy to authenticate with Google via OAuth2 in OmniAuth.

Get your API key at: https://code.google.com/apis/console/ Note the Client ID and the Client Secret.

For more details, read the Google docs: https://developers.google.com/accounts/docs/OAuth2

Installation

Add to your Gemfile:

gem 'omniauth-google-oauth2'

Then bundle install.

Google API Setup

  • Go to 'https://console.developers.google.com'
  • Select your project.
  • Go to Credentials, then select the "OAuth consent screen" tab on top, and provide an 'EMAIL ADDRESS' and a 'PRODUCT NAME'
  • Wait 10 minutes for changes to take effect.

Usage

Here's an example for adding the middleware to a Rails app in config/initializers/omniauth.rb:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET']
end
OmniAuth.config.allowed_request_methods = %i[get]

You can now access the OmniAuth Google OAuth2 URL: /auth/google_oauth2

For more examples please check out examples/omni_auth.rb

Using Devise? Skip the above and jump down to the Devise section! After setting up the provider via Devise, you can reference the confdiurations below.

NOTE: While developing your application, if you change the scope in the initializer you will need to restart your app server. Remember that either the 'email' or 'profile' scope is required!

Configuration

You can configure several options, which you pass in to the provider method via a hash:

  • scope: A comma-separated list of permissions you want to request from the user. See the Google OAuth 2.0 Playground for a full list of available permissions. Caveats:

    • The email and profile scopes are used by default. By defining your own scope, you override these defaults, but Google requires at least one of email or profile, so make sure to add at least one of them to your scope!
    • Scopes starting with https://www.googleapis.com/auth/ do not need that prefix specified. So while you can use the smaller scope books since that permission starts with the mentioned prefix, you should use the full scope URL https://docs.google.com/feeds/ to access a user's docs, for example.
  • redirect_uri: Override the redirect_uri used by the gem.

  • prompt: A space-delimited list of string values that determines whether the user is re-prompted for authentication and/or consent. Possible values are:

    • none: No authentication or consent pages will be displayed; it will return an error if the user is not already authenticated and has not pre-configured consent for the requested scopes. This can be used as a method to check for existing authentication and/or consent.
    • consent: The user will always be prompted for consent, even if they have previously allowed access a given set of scopes.
    • select_account: The user will always be prompted to select a user account. This allows a user who has multiple current account sessions to select one amongst them.

    If no value is specified, the user only sees the authentication page if they are not logged in and only sees the consent page the first time they authorize a given set of scopes.

  • image_aspect_ratio: The shape of the user's profile picture. Possible values are:

    • original: Picture maintains its original aspect ratio.
    • square: Picture presents equal width and height.

    Defaults to original.

  • image_size: The size of the user's profile picture. The image returned will have width equal to the given value and variable height, according to the image_aspect_ratio chosen. Additionally, a picture with specific width and height can be requested by setting this option to a hash with width and height as keys. If only width or height is specified, a picture whose width or height is closest to the requested size and requested aspect ratio will be returned. Defaults to the original width and height of the picture.

  • name: The name of the strategy. The default name is google_oauth2 but it can be changed to any value, for example google. The OmniAuth URL will thus change to /auth/google and the provider key in the auth hash will then return google.

  • access_type: Defaults to offline, so a refresh token is sent to be used when the user is not present at the browser. Can be set to online. More about offline access

  • hd: (Optional) Limit sign-in to a particular Google Apps hosted domain. This can be simply string 'domain.com' or an array %w(domain.com domain.co). More information at: https://developers.google.com/accounts/docs/OpenIDConnect#hd-param

  • jwt_leeway: Number of seconds passed to the JWT library as leeway. Defaults to 60 seconds. Note this only works if you use jwt 2.1, as the leeway option was removed in later versions.

  • skip_jwt: Skip JWT processing. This is for users who are seeing JWT decoding errors with the iat field. Always try adjusting the leeway before disabling JWT processing.

  • login_hint: When your app knows which user it is trying to authenticate, it can provide this parameter as a hint to the authentication server. Passing this hint suppresses the account chooser and either pre-fill the email box on the sign-in form, or select the proper session (if the user is using multiple sign-in), which can help you avoid problems that occur if your app logs in the wrong user account. The value can be either an email address or the sub string, which is equivalent to the user's Google+ ID.

  • include_granted_scopes: If this is provided with the value true, and the authorization request is granted, the authorization will include any previous authorizations granted to this user/application combination for other scopes. See Google's Incremental Authorization for additional details.

  • enable_granular_consent: If this is provided with the value true, users can choose to only grant access to specific data. See Google's How to handle granular permissions guide for additional details.

  • openid_realm: Set the OpenID realm value, to allow upgrading from OpenID based authentication to OAuth 2 based authentication. When this is set correctly an openid_id value will be set in ['extra']['id_info'] in the authentication hash with the value of the user's OpenID ID URL.

  • provider_ignores_state: You will need to set this to true when using the One-time Code Flow below. In this flow there is no server side redirect that would set the state.

  • overridable_authorize_options: By default, all authorize_options can be overridden with request parameters. You can restrict the behavior by using this option.

Here's an example of a possible configuration where the strategy name is changed, the user is asked for extra permissions, the user is always prompted to select their account when logging in and the user's profile picture is returned as a thumbnail:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'],
    {
      scope: 'email, profile, http://gdata.youtube.com',
      prompt: 'select_account',
      image_aspect_ratio: 'square',
      image_size: 50
    }
end

Auth Hash

Here's an example of an authentication hash available in the callback by accessing request.env['omniauth.auth']:

{
  "provider" => "google_oauth2",
  "uid" => "100000000000000000000",
  "info" => {
    "name" => "John Smith",
    "email" => "[email protected]",
    "first_name" => "John",
    "last_name" => "Smith",
    "image" => "https://lh4.googleusercontent.com/photo.jpg",
    "urls" => {
      "google" => "https://plus.google.com/+JohnSmith"
    }
  },
  "credentials" => {
    "token" => "TOKEN",
    "refresh_token" => "REFRESH_TOKEN",
    "expires_at" => 1496120719,
    "expires" => true
  },
  "extra" => {
    "id_token" => "ID_TOKEN",
    "id_info" => {
      "azp" => "APP_ID",
      "aud" => "APP_ID",
      "sub" => "100000000000000000000",
      "email" => "[email protected]",
      "email_verified" => true,
      "at_hash" => "HK6E_P6Dh8Y93mRNtsDB1Q",
      "iss" => "accounts.google.com",
      "iat" => 1496117119,
      "exp" => 1496120719
    },
    "raw_info" => {
      "sub" => "100000000000000000000",
      "name" => "John Smith",
      "given_name" => "John",
      "family_name" => "Smith",
      "profile" => "https://plus.google.com/+JohnSmith",
      "picture" => "https://lh4.googleusercontent.com/photo.jpg?sz=50",
      "email" => "[email protected]",
      "email_verified" => "true",
      "locale" => "en",
      "hd" => "company.com"
    }
  }
}

Devise

First define your application id and secret in config/initializers/devise.rb. Do not use the snippet mentioned in the Usage section.

Configuration options can be passed as the last parameter here as key/value pairs.

config.omniauth :google_oauth2, 'GOOGLE_CLIENT_ID', 'GOOGLE_CLIENT_SECRET', {}

NOTE: If you are using this gem with devise with above snippet in config/initializers/devise.rb then do not create config/initializers/omniauth.rb which will conflict with devise configurations.

Then add the following to 'config/routes.rb' so the callback routes are defined.

devise_for :users, controllers: { omniauth_callbacks: 'users/omniauth_callbacks' }

Make sure your model is omniauthable. Generally this is "/app/models/user.rb"

devise :omniauthable, omniauth_providers: [:google_oauth2]

Then make sure your callbacks controller is setup.

# app/controllers/users/omniauth_callbacks_controller.rb:

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def google_oauth2
      # You need to implement the method below in your model (e.g. app/models/user.rb)
      @user = User.from_omniauth(request.env['omniauth.auth'])

      if @user.persisted?
        flash[:notice] = I18n.t 'devise.omniauth_callbacks.success', kind: 'Google'
        sign_in_and_redirect @user, event: :authentication
      else
        session['devise.google_data'] = request.env['omniauth.auth'].except('extra') # Removing extra as it can overflow some session stores
        redirect_to new_user_registration_url, alert: @user.errors.full_messages.join("\n")
      end
  end
end

and bind to or create the user

def self.from_omniauth(access_token)
    data = access_token.info
    user = User.where(email: data['email']).first

    # Uncomment the section below if you want users to be created if they don't exist
    # unless user
    #     user = User.create(name: data['name'],
    #        email: data['email'],
    #        password: Devise.friendly_token[0,20]
    #     )
    # end
    user
end

For your views you can login using:

<%# omniauth-google-oauth2 1.0.x uses OmniAuth 2 and requires using HTTP Post to initiate authentication: %>
<%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path, method: :post %>

<%# omniauth-google-oauth2 prior 1.0.0: %>
<%= link_to "Sign in with Google", user_google_oauth2_omniauth_authorize_path %>

<%# Devise prior 4.1.0: %>
<%= link_to "Sign in with Google", user_omniauth_authorize_path(:google_oauth2) %>

An overview is available at https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview

One-time Code Flow (Hybrid Authentication)

Google describes the One-time Code Flow here. This hybrid authentication flow has significant functional and security advantages over a pure server-side or pure client-side flow. The following steps occur in this flow:

  1. The client (web browser) authenticates the user directly via Google's JS API. During this process assorted modals may be rendered by Google.
  2. On successful authentication, Google returns a one-time use code, which requires the Google client secret (which is only available server-side).
  3. Using a AJAX request, the code is POSTed to the Omniauth Google OAuth2 callback.
  4. The Omniauth Google OAuth2 gem will validate the code via a server-side request to Google. If the code is valid, then Google will return an access token and, if this is the first time this user is authenticating against this application, a refresh token. Both of these should be stored on the server. The response to the AJAX request indicates the success or failure of this process.

This flow is immune to replay attacks, and conveys no useful information to a man in the middle.

The omniauth-google-oauth2 gem supports this mode of operation when provider_ignores_state is set to true. Implementors simply need to add the appropriate JavaScript to their web page, and they can take advantage of this flow. An example JavaScript snippet follows.

// Basic hybrid auth example following the pattern at:
// https://developers.google.com/identity/sign-in/web/reference

<script src="https://apis.google.com/js/platform.js?onload=init" async defer></script>

...

function init() {
  gapi.load('auth2', function() {
    // Ready.
    $('.google-login-button').click(function(e) {
      e.preventDefault();

      gapi.auth2.authorize({
        client_id: 'YOUR_CLIENT_ID',
        cookie_policy: 'single_host_origin',
        scope: 'email profile',
        response_type: 'code'
      }, function(response) {
        if (response && !response.error) {
          // google authentication succeed, now post data to server.
          jQuery.ajax({type: 'POST', url: '/auth/google_oauth2/callback', data: response,
            success: function(data) {
              // response from server
            }
          });
        } else {
          // google authentication failed
        }
      });
    });
  });
};

Note about mobile clients (iOS, Android)

The documentation at https://developers.google.com/identity/sign-in/ios/offline-access specifies the REDIRECT_URI to be either a set value or an EMPTY string for mobile logins to work. Else, you will run into redirect_uri_mismatch errors.

In that case, ensure to send an additional parameter redirect_uri= (empty string) to the /auth/google_oauth2/callback URL from your mobile device.

Note about CORS

If you're making POST requests to /auth/google_oauth2/callback from another domain, then you need to make sure 'X-Requested-With': 'XMLHttpRequest' header is included with your request, otherwise your server might respond with OAuth2::Error, : Invalid Value error.

Getting around the redirect_uri_mismatch error (See Issue #365)

If you are struggling with a persistent redirect_uri_mismatch, you can instead pass the access_token from getAuthResponse directly to the auth/google_oauth2/callback endpoint, like so:

// Initialize the GoogleAuth object
let googleAuth;
gapi.load('client:auth2', async () => {
  await gapi.client.init({ scope: '...', client_id: '...' });
  googleAuth = gapi.auth2.getAuthInstance();
});

// Call this when the Google Sign In button is clicked
async function signInGoogle() {
  const googleUser = await googleAuth.signIn(); // wait for the user to authorize through the modal
  const { access_token } = googleUser.getAuthResponse();

  const data = new FormData();
  data.append('access_token', access_token);

  const response = await api.post('/auth/google_oauth2/callback', data)
  console.log(response);
}

Using Axios

If you're making a GET resquests from another domain using access_token.

axios
  .get(
    'url(path to your callback}',
    { params: { access_token: 'token' } },
    headers....
    )

If you're making a POST resquests from another domain using access_token.

axios
  .post(
    'url(path to your callback}',
    { access_token: 'token' },
    headers....
    )

--OR--

axios
  .post(
    'url(path to your callback}',
    null,
      {
        params: {
          access_token: 'token'
        },
        headers....
      }
    )

Fixing Protocol Mismatch for redirect_uri in Rails

Just set the full_host in OmniAuth based on the Rails.env.

# config/initializers/omniauth.rb
OmniAuth.config.full_host = Rails.env.production? ? 'https://domain.com' : 'http://localhost:3000'

License

Copyright (c) 2018 by Josh Ellithorpe

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

omniauth-google-oauth2's People

Contributors

abrom avatar afrankel avatar agilbert201 avatar ajsharp avatar alex88 avatar alexbartlow avatar alexgreat70 avatar andrewculver avatar asaaki avatar bbenezech avatar bradleybuda avatar chulkilee avatar davidtaylorhq avatar dr-impossible avatar dudemanvox avatar ened avatar guilhermesimoes avatar icambron avatar legendetm avatar mkdynamic avatar nhorton avatar ohrite avatar olivierlacan avatar pepusz avatar petergoldstein avatar samduvall avatar stanhu avatar taher-ghaleb avatar tomhughes avatar zquestz 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

omniauth-google-oauth2's Issues

Also not getting refresh token

Similarly to #16, I'm not receiving a refresh token -- only the token that expires after an hour. I'm not configuring this in devise, though. I'm configuring it separately as is done in the examples for this gem.

The line in my omni_auth.rb initializer is as follows:

provider :google_oauth2, client_id, client_secret, :scope => 'https://www.googleapis.com/auth/analytics.readonly', :display => 'popup'

I've tried pretty much every combination of approval_prompt and access_type, but to no avail.

The response I get back is as follows (sensitive fields filtered out):

{ :email => "[filtered]", :name=>"", :uid => "[filtered]", :provider => "Google_oauth2", :token => "[filtered]" }

warning: already initialized constant VERSION

Small thing; when I initialize the app I get the following warning:

...shared/bundle/ruby/1.8/bundler/gems/omniauth-google-oauth2-2bea080d89e5/lib/omniauth/google_oauth2/version.rb:3: warning: already initialized constant VERSION

But everything else works just fine, thanks!

Scope not being respected

In my config/initializers/omniauth.rb:

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, ENV["GOOGLE_KEY"], ENV["GOOGLE_SECRET"]
    {
      :scope => "userinfo.email,userinfo.profile,analytics.readonly",
      :approval_prompt => "auto"
    }
end

When I get to the auth screen on google, it's only asking me for userinfo.email and userinfo.profile permissions, and nothing for analytics.readonly.

Looking at the URL when I'm auth'ing, I can see that it's only requesting the first two permissions. If I manually add the analytics permission to the URL, it grants the correct permissions. So, I've narrowed the issue down to

  1. How I'm passing scope to the omniauth-google-oauth2 strategy, or
  2. How the strategy is handling the scope hash.

Also, I have double-checked that the Analytics API is turned on for my OAuth keys in the Google API Console.

invalid_client: { "error" : "invalid_client" }

When I try to use this it gets to the callback url (/auth/google_oauth2/callback) but shows this

OAuth2::Error

invalid_client: 
{
  "error" : "invalid_client"
}

Stack trace:

oauth2 (0.8.0) lib/oauth2/client.rb:108:in `request'
oauth2 (0.8.0) lib/oauth2/client.rb:131:in `get_token'
oauth2 (0.8.0) lib/oauth2/strategy/auth_code.rb:29:in `get_token'
omniauth-oauth2 (1.1.0) lib/omniauth/strategies/oauth2.rb:100:in `build_access_token'
omniauth-oauth2 (1.1.0) lib/omniauth/strategies/oauth2.rb:75:in `callback_phase'
omniauth (1.1.0) lib/omniauth/strategy.rb:219:in `callback_call'
omniauth (1.1.0) lib/omniauth/strategy.rb:175:in `call!'
omniauth (1.1.0) lib/omniauth/strategy.rb:157:in `call'
omniauth (1.1.0) lib/omniauth/strategy.rb:177:in `call!'
omniauth (1.1.0) lib/omniauth/strategy.rb:157:in `call'
omniauth (1.1.0) lib/omniauth/builder.rb:48:in `call'
actionpack (3.2.6) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
rack (1.4.1) lib/rack/etag.rb:23:in `call'
rack (1.4.1) lib/rack/conditionalget.rb:25:in `call'
actionpack (3.2.6) lib/action_dispatch/middleware/head.rb:14:in `call'
actionpack (3.2.6) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.2.6) lib/action_dispatch/middleware/flash.rb:242:in `call'
rack (1.4.1) lib/rack/session/abstract/id.rb:205:in `context'
rack (1.4.1) lib/rack/session/abstract/id.rb:200:in `call'
actionpack (3.2.6) lib/action_dispatch/middleware/cookies.rb:338:in `call'
activerecord (3.2.6) lib/active_record/query_cache.rb:64:in `call'
activerecord (3.2.6) lib/active_record/connection_adapters/abstract/connection_pool.rb:473:in `call'
actionpack (3.2.6) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
activesupport (3.2.6) lib/active_support/callbacks.rb:405:in `_run__221833846075497048__call__1546209218515107876__callbacks'
activesupport (3.2.6) lib/active_support/callbacks.rb:405:in `__run_callback'
activesupport (3.2.6) lib/active_support/callbacks.rb:385:in `_run_call_callbacks'
activesupport (3.2.6) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (3.2.6) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (3.2.6) lib/action_dispatch/middleware/reloader.rb:65:in `call'
actionpack (3.2.6) lib/action_dispatch/middleware/remote_ip.rb:31:in `call'
actionpack (3.2.6) lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call'
actionpack (3.2.6) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
railties (3.2.6) lib/rails/rack/logger.rb:26:in `call_app'
railties (3.2.6) lib/rails/rack/logger.rb:16:in `call'
actionpack (3.2.6) lib/action_dispatch/middleware/request_id.rb:22:in `call'
rack (1.4.1) lib/rack/methodoverride.rb:21:in `call'
rack (1.4.1) lib/rack/runtime.rb:17:in `call'
activesupport (3.2.6) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.4.1) lib/rack/lock.rb:15:in `call'
actionpack (3.2.6) lib/action_dispatch/middleware/static.rb:62:in `call'
railties (3.2.6) lib/rails/engine.rb:479:in `call'
railties (3.2.6) lib/rails/application.rb:220:in `call'
railties (3.2.6) lib/rails/railtie/configurable.rb:30:in `method_missing'
passenger (3.0.13) lib/phusion_passenger/rack/request_handler.rb:96:in `process_request'
passenger (3.0.13) lib/phusion_passenger/abstract_request_handler.rb:516:in `accept_and_process_next_request'
passenger (3.0.13) lib/phusion_passenger/abstract_request_handler.rb:274:in `main_loop'
passenger (3.0.13) lib/phusion_passenger/rack/application_spawner.rb:206:in `start_request_handler'
passenger (3.0.13) lib/phusion_passenger/rack/application_spawner.rb:171:in `block in handle_spawn_application'
passenger (3.0.13) lib/phusion_passenger/utils.rb:479:in `safe_fork'
passenger (3.0.13) lib/phusion_passenger/rack/application_spawner.rb:166:in `handle_spawn_application'
passenger (3.0.13) lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop'
passenger (3.0.13) lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously'
passenger (3.0.13) lib/phusion_passenger/abstract_server.rb:180:in `start'
passenger (3.0.13) lib/phusion_passenger/rack/application_spawner.rb:129:in `start'
passenger (3.0.13) lib/phusion_passenger/spawn_manager.rb:253:in `block (2 levels) in spawn_rack_application'
passenger (3.0.13) lib/phusion_passenger/abstract_server_collection.rb:132:in `lookup_or_add'
passenger (3.0.13) lib/phusion_passenger/spawn_manager.rb:246:in `block in spawn_rack_application'
passenger (3.0.13) lib/phusion_passenger/abstract_server_collection.rb:82:in `block in synchronize'
<internal:prelude>:10:in `synchronize'
passenger (3.0.13) lib/phusion_passenger/abstract_server_collection.rb:79:in `synchronize'
passenger (3.0.13) lib/phusion_passenger/spawn_manager.rb:244:in `spawn_rack_application'
passenger (3.0.13) lib/phusion_passenger/spawn_manager.rb:137:in `spawn_application'
passenger (3.0.13) lib/phusion_passenger/spawn_manager.rb:275:in `handle_spawn_application'
passenger (3.0.13) lib/phusion_passenger/abstract_server.rb:357:in `server_main_loop'
passenger (3.0.13) lib/phusion_passenger/abstract_server.rb:206:in `start_synchronously'
passenger (3.0.13) helper-scripts/passenger-spawn-server:99:in `<main>'

How to authenticate for a valid google analytics account

I'm using omniauth-google-oauth2 for authenticating to google and google app accounts.In my app users login with their google accounts to view their google analytics data.
Authenticaton is done properly when user logins correctly with a valid GA account but gives me error when the account is not registered with Google analytics as

{"errors"=>[{"domain"=>"global", "reason"=>"insufficientPermissions", "message"=>"User does not have any Google Analytics account."}], "code"=>403, "message"=>"User does not have any Google Analytics account."}:

Don't know how to handle this and redirect users back to the login page by giving an error message that "Account is not registered with GA"
screenshot from 2013-09-02 15 59 05

Scope 'plus.login' returns empty hash

First, I'll state my intention. I want to ask the user for their email, profile, and friends for my app. The combination of 'plus.login' and 'userinfo.email' scopes should do the trick.

However, I've come to understand that the 'plus.login' scope doesn't give you the user profile information when you call https://www.googleapis.com/oauth2/v1/userinfo :

(rdb:4) p puts access_token.get('https://www.googleapis.com/oauth2/v1/userinfo').parsed.to_yaml
--- 
id: "MY_ID"
email: myemail@gmail.com
verified_email: true

Instead, it does give you access to https://www.googleapis.com/plus/v1/people/me for the user profile information (gist here: https://gist.github.com/jtherrell/12843cfbd34e6c739834). This API does not have the same response data schema as https://www.googleapis.com/oauth2/v1/userinfo

I know I could add the userinfo.profile scope, but Google specifically advises not requesting userinfo.profile or plus.me scopes along with plus.login as it creates a confusing permissions dialog for the end-user (3rd paragraph in plus.login scope description: https://developers.google.com/+/api/oauth#scopes)

I'd be happy to work on this and submit a pull request, but I wanted to know if you'd be open to special case support for the 'plus.login' and 'userinfo.email' scope combination.

Example usage of the `scope` in the Readme

Looks like a few people (myself included) have been caught out by this.

Perhaps the readme should note that for scope:

  • You don't need the https://www.googleapis.com/auth/ prefix.
  • You provide several a , separated list, without spaces.
  • You need to give userinfo.email to get the email.

Not getting a refresh_token

I'm using version 0.1.9

My line in my devise.rb is the following:

{:scope=>"https://www.google.com/m8/feeds, 
https://www.googleapis.com/auth/userinfo.email, 
https://www.googleapis.com/auth/userinfo.profile", :approval_prompt=>""} 

I'm intentionally not setting :access_type and it should default to "offline"

When I get a response back I am logging out the result of: request.env['omniauth.auth']

and I am not seeing any refresh token. Here is the credentials part of that response:


credentials:
  token: xxx
  expires_at: 1329093395
  expires: true

Devise 3.0.0rc - Deprecation Warning

This gem either calls this itself or pull in something that does.
[DEVISE] Devise.use_salt_as_remember_token is deprecated and has no effect. Please remove it.

:request_visible_actions option seems to not work correctly.

I'm trying to setup a omniauth connection to post to an user GooglePlus feed. I have it setup with devise like this:

  devise_config.omniauth :google_oauth2, "CLIENT_ID", "CLIENT_SECRET",    scope: 'plus.login', request_visible_actions: 'http://schemas.google.com/AddActivity', access_type: 'offline'

I pickup the token from the request in the OmniauthCallbacksController. Later I try to use that token to post an activity to G+, with the google_api_client gem but I get an Unauthorized error when I try:

  @google_client ||= Google::APIClient.new
  @google_client.authorization.client_id = GOOGLE_OAUTH2_ID
  @google_client.authorization.client_secret = GOOGLE_OAUTH2_SECRET
  @google_client.authorization.access_token = token #this is the token returned in the callback

  plus = client.discovered_api('plus')

  moment = {
      type: 'http://schemas.google.com/AddActivity',
      target: {
          id: Time.now.to_i.to_s,
          description: 'moment description',
          name: 'moment name'
       }
   }

  client.execute( {api_method: plus.moments.insert, parameters: {collection: 'vault', userId: 'me', debug: true}, body_object: moment }  )

As far as I know this should work if the request_visible_actions is sent correctly, but it seems not. I tried another activity that require authorization but no request_visible_actions, moments.list, and it seems like it works even it return nil (since no moments haven't been post by the app yet...)

Any help on this?

Its been posted on stackoverflow recently too:
http://stackoverflow.com/questions/16453252/rails-omniauth-google-oauth2-google-api-client-moments-insert-401-unautho

access type offline fails

I'm trying to get offline access token

This is my initializer code:

Rails.application.config.middleware.use OmniAuth::Builder do
   provider :google_oauth2, KEY, SECRET,
   :access_type => 'offline', 
   :scope => 'https://www.googleapis.com/auth/userinfo.profile'
end

When redirecting to google, it should add an extra URL parameter &access_type=offline, but it fails to do so (it works fine if I add the parameter manually on the address bar).

Is this a bug or am I missing something?

https support?

I'd like to use https for my callback redirect_uri. I set it in my Google app configuration, but I get this error on authentication:

Error: redirect_uri_mismatch
The redirect URI in the request: http://example.com/users/auth/google_oauth2/callback did not match a registered redirect URI
...

If I set it to http in my app, then it works, but would prefer https. Looking at your source code as well as Omniauth, but can't find anything that sets the initial request to Google.

Note: I'm also using Devise's Omniauth integration.

invalid scope when listing multiple scopes

I just updated to the version 0.1.18 and my auth request all of a sudden broke without any changes in my code. The error I get from Google is:

Error: invalid_scope
Some requested scopes were invalid. {invalid=[https://www.googleapis.com/auth/userinfo.emailhttps://www.googleapis.com/auth/calendar]}

It seems that the space between the scope arguments is missing. I think this is due to the commit f070eb6.

Possible to dynamically set (:prompt => 'select_account consent')?

I'm trying to obtain the refresh_token for existing users that have google authenticated.

I could set my omniauth.rb to:

:prompt => 'select_account consent'

The problem is that change would force all users to go through those extra 2 steps. Is there a way to dynamically set (:prompt => 'select_account consent') only if a condition was met?

Thanks

The action 'google_oauth2' could not be found for Users::OmniauthCallbacksController

Hi,

I'm using 'omniauth-google-oauth2' for sign in with google and follow all instruction here carefully

    https://github.com/plataformatec/devise/wiki/OmniAuth%3A-Overview

but i have error above.

I have also try with 'omniauth-google' gem but same kind of error. i Have created issue for it also here.

    https://github.com/Yesware/omniauth-google/issues/9

it seems like both are same erorrs method missing.

Can you please help?

Invalid client

Sorry, but I seem to be missing something obvious here. I'm a newbie.

I have the following config (using devise, omniauth):

config.omniauth :google_oauth2, "[my key]", "[secret]", {access_type: 'online', approval_prompt: ''}

[my key] above also happens to equal [my domain]

I get 400 Bad Request:

Error: invalid_client
Request Details
response_type=code
scope=https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile
redirect_uri=https://[my domain]/users/auth/google_oauth2/callback
access_type=online
client_id=[my domain]

I think it has to do with one of a few possibilities:

  1. I have ssl on my app and I'm wondering if I need to pass additional parms.

  2. I am not using the right key/secret. I have found 3 places on google (apps) to set up oauth keys:
    a) https://accounts.google.com/ManageDomains - where I have it set up and I'm using this key/secret
    b) https://code.google.com/apis/console - where I have it set up but I'm NOT using this key/secret
    c) https://www.google.com/a/cpanel/[mydomain]/SetupOAuth - I am NOT using this one.

What am I missing?

Thanks in advance.

Not working on Heroku apps

I am trying to use Google Apps authentication for an app that will be hosted on Heroku.com

Everything works great locally, but once I try on Heroku it doesn't works. Google will always return to the auth failure url.

According to Devise Wiki:

If your app is running on Heroku (and you have been pulling your hair out for hours), the config section needs to look like this:

config.omniauth :facebook, "APP_ID", "APP_SECRET",
      {:scope => 'email, offline_access', :client_options => {:ssl => {:ca_file => '/usr/lib/ssl/certs/ca-certificates.crt'}}} 

On Engine Yard Cloud servers, the CA file is located at /etc/ssl/certs/ca-certificates.crt.

How can I make my middleware config use the ssl option?

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, ENV['GOOGLE_APP_ID'], ENV['GOOGLE_SECRET_KEY']
end

UID from Google not matching UID when users first created their accounts

This is probably not an issue with this gem, but I'm running into dead ends, and I'm hopeful that you can help.

Users of our web app who created their accounts using Google Oauth2 have recently stopped being able to log in. I can reproduce the problem in development, and observed that the Google callback is now sending a different UID than it did when I first created my account many months ago. Users who created their accounts more recently are also unable to sign in. But users who create new accounts today are able to log in just fine.

Is it possible that Google has changed something on their end? We have not changed our "Client secret" or our "Redirect urls" on Google, nor have we updated our gem (though I did try updating from 0.1.13 to 0.1.17 after discovering this problem...to no avail).

Changelog

Could you provide a changelog for this project?

I ended up doing a simple comparison between 0.2.0 and 0.2.1 but services like Gemnasium parse changelogs making it much simpler to stay on top of dependencies.

Thank you πŸ˜ƒ

StrategyNotFound

After I have added entry to 'devise.rb':

config.omniauth :google_oauth2, APP_ID, APP_SECRED...

I saw this exception:

C:/RailsInstaller/Ruby1.9.2/lib/ruby/gems/1.9.1/gems/devise-1.5.2/lib/devise/omniauth/config.rb:40:in 'autoload_strategy':
Could not find a strategy with name 'GoogleOAuth2'.
Please ensure it is required or explicitly set it using the :strategy_class option. (Devise::OmniAuth::StrategyNotFound)

I investigated devise/omniauth/config.rb:

OmniAuth::Utils.camelize(provider.to_s)

and in C:\RailsInstaller\Ruby1.9.2\lib\ruby\gems\1.9.1\gems\omniauth-1.0.1\lib\omniauth.rb:

camelize() method return: GoogleOAuth2 not GoogleOauth2!

After manual modification in:

C:\RailsInstaller\Ruby1.9.2\lib\ruby\gems\1.9.1\gems\omniauth-google-oauth2-0.1.8\lib\omniauth\strategies\google_oauth2.rb
Class name from 'GoogleOauth2' to 'GoogleOAuth2' it runs without exeption

I dont know if this is strategy issue or omniauth.

omniauth (1.0.1)
omniauth-google-oauth2 (0.1.8)
devise (1.5.2)

Best Regards,
Konrad.

Name field should be user's real name instead of email, if possible

Currently, all the keys in the info hash returned in the callback phase are being set to the authenticated user's email address. It would be more useful if the name key was set to the user's real name instead.

I did some digging around in both Google's documentation and OmniAuth's documentation, and there doesn't seem to be an obvious way to do this – at least not as cleanly as with Facebook and Twitter. You can get more information about the authenticated user via the Google+ API using the API endpoint at https://www.googleapis.com/plus/v1/people/me, but I believe this requires that the user be signed up for Google+.

Any ideas on how to implement this? It's not clear which of the Google APIs is most suitable for retrieving basic data about a user account.

/cc @mbleigh

Image not showing up in request.env['omniauth.auth']

I am setting up devise, omniauth-google-oauth2, and omniauth-facebook. I have gotten images from facebook but when I use google the images isn't showing. Here's my hash of request.env['omniauth.auth'].to_yaml. (I blanked the email and token)

provider: :google
uid: '111920438680541876508'
info: !ruby/hash:OmniAuth::AuthHash::InfoHash
name: Jared Drewa
email:
first_name: Jared
last_name: Drewa
credentials: !ruby/hash:OmniAuth::AuthHash
token:
expires_at: 1388259836
expires: true
extra: !ruby/hash:OmniAuth::AuthHash
raw_info: !ruby/hash:OmniAuth::AuthHash
id: '111920438680541876508'
email:
verified_email: true
name: Jared Drewa
given_name: Jared
family_name: Drewa
locale: en
hd: musicfestivalnation.com

I don't know why the image isn't showing.
I have tried adding this to my config:
:image_aspect_ratio => "square",
:image_size => 50

This didn't change anything though. Any ideas why this isn't working?

How to reset omniauth-google-oauth2 access_token when user account has been removed

We are encountering an issue where if the user's account has been deleted from system after the user already granted access to the application from his google account, the authentication just goes in an endless loop of trying to authenticate the deleted user.

The scenario goes something like:

  1. The user authenticates via google and grants access for the application
  2. In the callback, our application determines if the user account is valid - deleted, or not created (our system does not support self service registration
  3. The user is not authorised (and not signed in) which is correct
  4. If the user attempts to sign-in via Google again, to try another account, Google transparently authorizes and redirects the user back to our application without giving the user a chance to change accounts.

The user can actually get out of this loop by logging out of first. But that's not really obvious to the average user so is not an ideal solution.

Ideally, the solution would be to invalidate the access_token or revoke the application authorization in the callback phase so that when the user tries to sign in again they can switch accounts.

Authentication failure! for bigquery scope

Trying to use this for bigquery api service like this:
use OmniAuth::Builder do
provider :google_oauth2, CLIENT_ID, CLIENT_SECRET, {:scope => 'https://www.googleapis.com/auth/bigquery', :access_type => 'online', :approval_prompt => ''}
end

It fails with:

, [2012-05-10T16:59:07.028592 #82585] ERROR -- omniauth: (google_oauth2) Authentication failure! invalid_credentials: OAuth2::Error, {"errors"=>[{"domain"=>"com.google.auth", "reason"=>"invalidAuthentication", "message"=>"invalid token", "locationType"=>"header", "location"=>"Authorization"}], "code"=>401, "message"=>"invalid token"}:
{
"error": {
"errors": [
{
"domain": "com.google.auth",
"reason": "invalidAuthentication",
"message": "invalid token",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "invalid token"
}
}

After getting pas the auth screen: http://cl.ly/411r281w0x3h162I000a

Any ideas?

It works of course when I remove the scope, when it defaults to user:profile scope.

cannot load such file -- omniauth/google/oauth2 (LoadError)

Hi,
just by including the gem in my Gemfile:

gem 'omniauth-google-oauth2'

I get the following error:

21:20:05 web.1  | started with pid 20590
21:20:14 web.1  | /Users/user/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.2.1/lib/bundler/runtime.rb:74:in `require': cannot load such file -- omniauth/google/oauth2 (LoadError)
21:20:14 web.1  |   from /Users/user/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.2.1/lib/bundler/runtime.rb:74:in `rescue in block in require'
21:20:14 web.1  |   from /Users/user/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.2.1/lib/bundler/runtime.rb:62:in `block in require'
21:20:14 web.1  |   from /Users/user/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.2.1/lib/bundler/runtime.rb:55:in `each'
21:20:14 web.1  |   from /Users/user/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.2.1/lib/bundler/runtime.rb:55:in `require'
21:20:14 web.1  |   from /Users/user/.rvm/gems/ruby-1.9.3-p125/gems/bundler-1.2.1/lib/bundler.rb:128:in `require'
21:20:14 web.1  |   from /Users/user/Sites/WISDOM/code/git/wisdom/config/application.rb:7:in `<top (required)>'
21:20:14 web.1  |   from /Users/user/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.11/lib/rails/commands.rb:53:in `require'
21:20:14 web.1  |   from /Users/user/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.11/lib/rails/commands.rb:53:in `block in <top (required)>'
21:20:14 web.1  |   from /Users/user/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.11/lib/rails/commands.rb:50:in `tap'
21:20:14 web.1  |   from /Users/user/.rvm/gems/ruby-1.9.3-p125/gems/railties-3.2.11/lib/rails/commands.rb:50:in `<top (required)>'
21:20:14 web.1  |   from script/rails:6:in `require'
21:20:14 web.1  |   from script/rails:6:in `<main>'
21:20:14 web.1  | exited with code 1
21:20:14 system | sending SIGTERM to all processes
SIGTERM received

I use the following gems:

oauth2 (0.9.2)
rails (3.2.11)
devise (3.0.0)

I have seen this issue
#32
but upgrading devise didn't help in this case.

Any idea what could be the issue?

:config => scope misparsed

Under Devise / OmniAuth, the following line:

config.omniauth :google_oauth2, KEY, SECRET, :scope => "userinfo.email,userinfo.profile"

… results in the following error from Google:

  OAuth 2.0 error: invalid_scope

  Some requested scopes were invalid. {valid=[https://www.googleapis.com/auth/userinfo.email], invalid=[userinfo.email,userinfo.profile]}

  OAuth2 Request Details
  response_type=code
  [redacted]
  access_type=offline
  scope=https://www.googleapis.com/auth/userinfo.email userinfo.email,userinfo.profile

It seems like the scope parsing code isn't being hit, because leaving off the :scope parameter works fine.

Need Username

I am not able to find username/login in response after connecting via google, kindly let me know how can I find username ever I have defined this scope:

scope: "https://mail.google.com/mail/feed/atom/, userinfo.email, userinfo.username, plus.me, https://www.googleapis.com/auth/userinfo.profile, http://gdata.youtube.com, http://sites.google.com/feeds/"

kindly guide me, thanks.

Bad request when customizing scope

When customizing the scope parameter like this:

scope: "userinfo.email,userinfo.profile"

You will get a 400 Bad Request error:

Some requested scopes were invalid. {valid=[https://www.googleapis.com/auth/userinfo.email], invalid=[userinfo.email,userinfo.profile]}

Missing port on callback

Hi,

I've just started working with Google authentication. I found an example of calling OAuth2 manually, which I have working. When I try to use OmniAuth with omniauth-google-oauth2 with the example provided in this GEM, I get a Sintra/HTTP error saying that it can't find the 'callback' path. I've traced the issue to gem trying to go to localhost/auth/google_oauth2/callback. My Google API console and Sinatra app are set to localhost:9292/auth/google_oauth2/callback. I can't find why or where that value is getting set in the GEM.

I'm hoping this is a simple silly mistake on my part. Could you provide any insight as to what I might be doing wrong.

Code:
get '/auth/:provider/callback' do
content_type 'text/plain'
request.env['omniauth.auth'].to_hash.inspect rescue "No Data"
end

Error:
SocketError at /auth/google_oauth2/callback
getaddrinfo: Name or service not known

Ruby /home/robert/.rvm/rubies/ruby-1.9.3-p0/lib/ruby/1.9.1/net/http.rb: in initialize, line 762
Web GET localhost/auth/google_oauth2/callback

uninitialized constant OmniAuth::Strategies::GoogleOauth2

Hi!

For following configuration:
provider :google_oauth2, key, secret
I got following error:
omniauth-1.0.0/lib/omniauth/builder.rb:22:in `const_get': uninitialized constant OmniAuth::Strategies::GoogleOauth2

But everything is ok for:
provider :google_oAuth2, key, secret

Probably you need add this to readme(examples) or fix.

Thanks.

Invalid grant with Devise 2.2.4 with Rails 3.2.13

Hi

I know that the invalid_grant issue has been discussed a few times in this board and I have followed through the discussisons but none of it seems to work?

I have a rails 3.2.13 app running devise and am using omniauth-google-oauth2 version 0.1.17 within the devise initialiser block. The user is allowed to authenticate but upon callback it shows an 'Invalid credentials' error even though the settings are correct?

Below is the line i used for the google_oauth2 strategy:

config.omniauth :google_oauth2, "XXXX", "CCCC", :scope=> "userinfo.email,userinfo.profile", :access_type=> "offline", :approval_prompt=> "auto"

I also have both twitter and facebook strategies working fine ?

any help is greatly appreciated

How do you integrate apppackagename into oauth2

Google has launched android app installs via google+ login https://developers.google.com/+/web/signin/android-app-installs.

I have managed to get google+ login work seamlessly with google_oauth2 by tweaking the scope. So far so good. Now I am trying to get the app to download with login .. For this the document says

"Add the data-apppackagename parameter to your HTML button or the apppackagename parameter to your object parameters. Specify your Android app's package name as the value. This value should be the same as the value that you entered in the APIs Console for the Android app that you want your users to download"

I have done all the config on the API console, added my apps package name, and verified my keys work etc. etc. but no dice with the prompt to install the app. My question is how do I pass the apppackagename parameter, For reference my scrubbed config is below ...

config.omniauth :google_oauth2, "key", "secret", {:access_type => 'online', :approval_prompt => '',:apppackagename => "com.myapp", :scope=>"userinfo.email,plus.me,plus.login"}

Is this the correct way to pass the parameter to Google ?

Dynamic providers error, client_id not found

Hi,
Currently I'm working with dynamic providers (https://github.com/intridea/omniauth/wiki/Dynamic-Providers), but google keeps saying:

Error: invalid_request
Missing required parameter: client_id

This is my omniauth.rb:

Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, :setup => true
provider :twitter,:setup => true
provider :linkedin,:setup => true
provider :foursquare, :setup => true
provider :google_oauth2, :setup => true
end

This is my setup method:

def setup_google
request.env['omniauth.strategy'].options[:client_id] = @site.google_client_id
request.env['omniauth.strategy'].options[:client_secret] = @site.google_client_secret

render :text => "Setup complete.", :status => 404

end

I made it work with facebook, twitter, linkedin and foursquare. It not seems to be a routes problem, I done it right for all the others strategies, but with google keeps failing.

What am I missing? any clue o this?

Thanks in advance.

No route matches [GET] "/auth/google"

Hi,

I hope it's the right place to talk about this. I need to this to work urgently (sorry for using that word)

I have a rails 3.1 application on ruby 1.9.3, I followed the example application here, and I also followed the railscasts one, but when I try to log in by calling /auth/google I get this error

No route matches [GET] "/auth/google"

I'm lost, since I use OmniAuth + openid + devise (3.1/1.9.3) in another application and it works, so I know there is nothing wrong with the service or accounts.

Please help.

Successful callback (with 'code' parameter) is failing

It looks like my request to google is succeeding, and it's returning an access code, but that is being picked up by omniauth #failure

http://localhost:3000/users/auth/google_oauth2/callback?code=4/pAGHqRxLK172Ur94C0P7MI0akJu9.kr1YoaqxPgMasNf4jSVKMpZYV-65cQI

Using devise + omniauth 1.0.2

Any ideas why?

Mysteriously stopped getting the refresh token when I requested access_type: 'offline'

Recently I've tried using my app which uses the omniauth-google-oauth2 gem today and noticed that I'm no longer getting the request.env['omniauth.auth][:credentials][:refresh_token] back in my callback. I do get a token but not the refresh token. This used to all work. I've verified that I have my access_type: 'offline'. Is there something that changed? Is anyone else running into this problem? Or is it just me?

`access_type: 'online'` not working

Using the example app with the following suggested configuration:

use OmniAuth::Builder do
  # For additional provider examples please look at 'omni_auth.rb'
  provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], {
    :access_type => 'online',
    :prompt => ''
  }
end

The first time that I login I get this prompt, as expected:

image

But if I open a new incognito window and login as the same Google user, then I get this prompt:

image

I'm able to click "Accept" and the callback is successful. But since I'm not requesting offline access I would expect to not get this message. I continue to see the prompt about "offline access" for all subsequent logins.

Is there a way to avoid the prompt about "offline access"? My goal is to use this gem for authentication only. I have no need for offline access.

Thanks!

missing refresh_token

Hello,
I upgraded the gem a while ago and now I don't receive any refresh_token.
Thousand of users requests are failing now because of this and I didn't noticed in time.

  provider :google_oauth2, Settings.services.youtube.client_key, Settings.services.youtube.client_secret, {
    scope: 'http://gdata.youtube.com,plus.me,drive,userinfo.email,userinfo.profile,glass.timeline',
    access_type: 'offline',
    prompt: 'select_account',
    client_options: {
      ssl: {
        ca_file: "#{Rails.root}/config/keys/curl-ca-bundle.crt"
      }
    }
  }

How to use domain name in the callback url using omniauth-google

Hi I'm using this gem to authenticate users in my application through google and google app, for this I have created client ID and secret on google api console https://code.google.com site.
For redirect URI I have added http://127.0.0.1:3000/users/auth/google_oauth2/callback.This seems to work like a charm,but the issue arises when I host my app on a web server like nginx wherein my server_name is www.abc.com. Application loads but when I try to login into app using google it gives me error as A refresh_token is not available because it is not able to get the request.env["omniauth.auth"].credentials['refresh_token'].

Don't know where I'm going wrong, is there any other configs that needs to be set

State param conflicts with omniauth-oauth2 CSRF protection?

I was just looking into using the new 'state' param as a way to send some additional data to the callbacks, but it seems to cause invalid_credentials errors. I just started digging the sources and discovered that omniauth-oauth2 latest 1.1.0 includes some CSRF protection using the same state param.

Could this thing be the cause of invalid_credentials when setting the 'state' param to something custom?

The action 'google_oauth2' could not be found for Users::OmniauthCallbacksController

Hi,

I'm using 'omniauth-google-oauth2' for sign in with google and follow all instruction here carefully

    https://github.com/plataformatec/devise/wiki/OmniAuth%3A-Overview

but i have error above.

my routes

devise_for :users, :controllers => {
:omniauth_callbacks => "users/omniauth_callbacks"

}

devise.rb code

config.omniauth :google_oauth2, "863625299460-420n6c7lvad91dfvko60uamtvtr6huhf.apps.googleusercontent.com", "dcvA2aZRZi27KCQjWTYP30pw", { access_type: "offline", approval_prompt: "" }

omniauth callback controller code

        def google_oauth2
        @user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user)

    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
      sign_in_and_redirect @user, :event => :authentication
    else
      session["devise.google_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
end

Can you please help?

see screenshot below

sss

OAuth Token Secret not being returned

I'm trying to use this strategy to get Gmail email with gmail_xoauth but env['omniauth.auth'] object doesn't have a token_secret, only a token. I've set the scope to include the mail one and the userinfo.email without any luck.

I was able to get a valid token and token secret with this tutorial: http://blog.asif.in/blog/2012/03/03/google-oauth-and-rails/ but this seems like almost a different strategy, any reason why this doesn't work or am I thinking about what this is supposed to do incorrectly?

Rails 4 - Action not found for Devise::OmniauthCallbacksController

I'm running Rails 4 with the devise 3.0.0rc and I get The action 'google_oauth2' could not be found for Devise::OmniauthCallbacksController on the callback.

source 'https://rubygems.org'ruby '2.0.0'

gem "compass-rails", github: "milgner/compass-rails", branch: "rails4"
gem 'asset_sync'
gem 'bootstrap-sass'
gem 'carrierwave'
gem 'coffee-rails', '>= 4.0.0'
gem 'devise', '3.0.0rc'
gem 'draper'
gem 'font-awesome-sass-rails'
gem 'foreman'
gem 'high_voltage'
gem 'jquery-rails'
gem 'mini_magick'
gem 'omniauth-google-oauth2', github: 'zquestz/omniauth-google-oauth2'
gem 'pg'
gem 'rails', '4.0.0.rc2'
gem 'redcarpet'
gem 'sass-rails', '4.0.0.rc2'
gem 'slim-rails'
gem 'susy'
gem 'turbolinks'
gem 'uglifier', '>= 1.3.0'
gem 'unicorn'

group :doc do
  gem 'sdoc', require: false
end

group :test, :development do
  gem 'dotenv'
  gem 'rspec-rails'
  gem 'factory_girl_rails'
  gem 'forgery'
  gem 'zonebie'
end
group :test do
  gem 'capybara'
  gem 'launchy'
  gem 'database_cleaner'
  gem 'capybara-webkit'
  gem 'simplecov'
end

Prefilling Google Account e-mail field

Hello,
It is possible to prefill the sign in form by appending Email param: click

How can I do this using the path helper in Rails user_omniauth_authorize_path(:google_oauth2)?

Thanks

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.