Rails: Twitter Omniauth gem 401 Unauthorized Error - ruby-on-rails

I am using twitter omniauth gem in my web application. I stored my key and secret in my DB.
This is my middleware code
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter, lambda { Site.config[:twitter][:key] },lambda{ Site.config[:twitter][:secret] }
end
This returns unauthorized error.
But when i specify my key and secret directly in the middleware it works.
(i.e)
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter, "consumer_key" , "consumer_secret"
end
What is wrong with my first approach ?

You need to use Setup Phase
provider :twitter, :setup => true
And then in controller:
def setup
request.env['omniauth.strategy'].options[:consumer_key] = Site.config[:twitter][:key]
request.env['omniauth.strategy'].options[:consumer_secret] = Site.config[:twitter][:secret]
render :text => "Setup complete.", :status => 404
end
Routes:
match '/auth/:provider/setup' => 'sessions#setup' # for example

You can add your consumer_key and consumer secret in the development.rb and production.rb
# twitter api credential
config.twitt_consumer_key = 'xxxxxxxxxxxxxxxxx'
config.twitt_consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
And then you can use it
provider :twitter, Rails.application.config.twitt_consumer_key, Rails.application.config.twitt_consumer_secret

Related

retrieve first_name and last_name from auth hash using omniauth-google-oauth2 gem

I have a rails 4.2.7 app setup using the omniauth-google-oauth2 gem, and I would like to retrieve the first_name and last_name from the auth hash.
I was able to do this with the omniauth-facebook gem by modifying the devise.rb to look like the following,
devise.rb
# Omniauth / Oauth2 settings
callback_url = if Rails.env == "development"
ENV['FB_CALLBACK']
else
ENV['FB_CALLBACK_PROD']
end
config.omniauth :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'], callback_url: callback_url,
:scope => 'email',
:info_fields => 'email, first_name, last_name'
# Google - OmniAuth
require 'omniauth-google-oauth2'
config.omniauth :google_oauth2, ENV["GOOGLE_CLIENT_ID"], ENV["GOOGLE_CLIENT_SECRET"]
However, I can't seem to figure out how to retrieve the first_name / last_name using omniauth-google-oauth2. Any help would greatly be appreciated.
#chris from omniauth-google-oauth2, in your callback controller action,
auth = request.env['omniauth.auth']
request.env['omniauth.auth'] will contain a hash of users' auth session, with which basic user info are persisted in info i.e. auth["info"]
auth
====
{
.....
"info"=>
{"name"=>"Username",
"email"=>"Useremail",
"first_name"=>"firstname",
"last_name"=>"lastname",
"image"=> "image_url",
"urls"=>{"Google"=>"https://plus.google.com/xxxxxxxxxxxxxxxxx"}
}
....
}

Oauth 2 "redirect_uri_mismatch: { "error" : "redirect_uri_mismatch" }" in rails

I am using oauth2 gem for google login auth. My code looks like
omniauth.rb
OmniAuth.config.logger = Rails.logger
require "omniauth-google-oauth2"
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, 'secret-client-id', 'secret-number', {client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}}}
end
my routes.rb
get 'auth/:provider/callback', to: 'sessions#create'
get 'auth/failure', to: redirect('/')
my view
<%= link_to "Sign in with Google", "/auth/google_oauth2", id: "sign_in" %>
I am getting this URL after this pages
Where am i going wrong?
Try adding token to the omniauth initializer:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, "id", "secret", {
client_options: {ssl: {ca_file: Rails.root.join("cacert.pem").to_s}},
scope: 'email profile',
access_type: 'online',
setup: (lambda do |env|
request = Rack::Request.new(env)
env['omniauth.strategy'].options['token_params'] = {:redirect_uri => 'http://.../auth/google_oauth2/callback'}
end)
}
end

request.env['omniauth.auth'] is always nil when using seperate admin login using omniauth-identity gem

I want to use seperate admin login for my application using idenity provider.
I have written this in config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :identity, :model => Credential, :on_failed_registration =>SessionsController.action(:register)
provider :identity, :model => Credential, :name => 'admin', :on_failed_registration => SessionsController.action(:login_admin)
provider :google_oauth2, '000000000.apps.googleusercontent.com', '00000000000'
end
In config/routes.rb
match '/auth/admin/callback', :to => 'sessions#authenticate_admin'
In app/controllers/sessions_controller.rb
def authenticate_admin
auth_hash = request.env['omniauth.auth']
session[:admin_user] = auth_hash['user_info']['email']
if admin?
redirect_to '/'
else
render :text => '401 Unauthorized', :status => 401
end
end
But when i try to access request.env['omniauth.auth'], it always gets nil. While it is accessible when using default callback for normal users at sessison#create action. I just want to know if there is anything that has been missed in this code. I am following this blog http://www.intridea.com/blog/2011/1/31/easy-rails-admin-login-with-google-apps-and-omniauth.

Get facebook app id from config/initializers/devise.rb

I've set my facebook app id in config/initializers/devise.rb and now i'm trying to retrieve it in my controller.
How do I call it back?
Devise.setup do |config|
config.omniauth :facebook, 'XXXXXX', 'XXXXX', :scope => 'email,offline_access,user_likes,user_interests,publish_actions,publish_stream'
end
Devise.omniauth_configs[:facebook].strategy.client_id

omniauth OAuthException & OAuth::Unauthorized

I have installed omniauth 1.0. Also I have oauth-0.4.5, oauth2-0.5.1, omniauth-facebook-1.0.0, omniauth-twitter-0.0.6.
omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :developer unless Rails.env.production?
provider :facebook, ENV['167257285348131'], ENV['c8c722f697scb2afcf1600286c6212a9'], :scope => 'email,offline_access,read_stream', :display => 'popup'
provider :twitter, ENV['fma2L22ObJCW52QrL7uew'], ENV['4aZfhCAOdiS7ap8pHJ7I1OZslFwVWWLiAMVpYUI']
end
session_controller.rb
class SessionsController < ApplicationController
require 'omniauth-facebook'
require 'omniauth-twitter'
require 'omniauth'
def create
#user = User.find_or_create_from_auth_hash(auth_hash)
self.current_user = #user
redirect_to '/'
end
def auth_hash
request.env['omniauth.auth']
end
end
Also I add
'omniauth'
'omniauth-facebook'
'omniauth-twitter' gems to gemfile
There are two problems:
When I go http://localhost:3000/auth/facebook I get
{
"error": {
"message": "Missing client_id parameter.",
"type": "OAuthException"
}
}
And the link graph.facebook.com/oauth/authorize?response_type=code&client_id=&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Ffacebook%2Fcallback&parse=query&scope=email%2Coffline_access%2Cread_stream&display=popup
And there is no client_id!!!
When I go to http://localhost:3000/auth/twitter I get OAuth::Unauthorized
401 Unauthorized
Any ideas?
Alex D. is correct in that the ENV[] breaks it. To create omniauth.rb so that it uses different keys in different environments just put:
provider :twitter, TWITTER_KEY, TWITTER_SECRET
in omniauth.rb
and then in your environment config files (config/environments/development.rb, etc.) put the key you want to use for that environment.
config/environments/development.rb:
TWITTER_KEY = 'aaaaaaa'
TWITTER_SECRET = 'aaaabbbbbb'
config/environments/production.rb:
TWITTER_KEY = 'ccccccc'
TWITTER_SECRET = 'ccccdddddd'
ENV['something']
looks into your environment vars for "something", so it would expect
something='12345'
so you should do it like that
export AUTH_FB_KEY='....'
export AUTH_FB_SECRET='...'
check with
env
and update your config
provider :facebook, ENV['AUTH_FB_KEY'], ENV['AUTH_FB_SECRET']
if you use heroku
heroku config:add AUTH_FB_KEY='....'
There have been breaking changes made in omniauth 1.0 - https://github.com/intridea/omniauth
OmniAuth 1.0 has several breaking changes from version 0.x. You can
set the dependency to ~> 0.3.2 if you do not wish to make the more
difficult upgrade. See the wiki for more information.
I would try reverting omniauth to 0.3.2:
gem install omniauth --version '~> 0.3.2'
or if you're using bundler, in your Gemfile:
gem omniauth, '~> 0.3.2'

Resources