ERROR: Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
My code :
#client = Signet::OAuth2::Client.new(
:authorization_uri => 'https://accounts.google.com/o/oauth2/auth',
:token_credential_uri => 'https://oauth2.googleapis.com/token',
:client_id => ENV['GMB_CLIENT_ID'],
:client_secret => ENV['GMB_CLIENT_SECRET'],
:scope => 'https://www.googleapis.com/auth/youtube.upload',
:redirect_uri => 'https://localhost:4200/youtube'
)
# a = my user with token and refresh token got from signet oAuth with google
response = {
"access_token" => a.token,
"refresh_token" => a.refresh_token,
"expries_in" => total_second,
"scope" => "https://www.googleapis.com/auth/youtube.upload",
"token_type" => "Bearer"
}
#client.update!(response)
#service ||= Google::Apis::YoutubeV3::YouTubeService.new
#service.key = "my key"
#service.authorization = #client #setting the authorization for api
status = Google::Apis::YoutubeV3::VideoStatus.new(
privacy_status: 'unlisted',
)
snippet = Google::Apis::YoutubeV3::VideoSnippet.new(
title: "My video",
description: "description",
)
video_object = Google::Apis::YoutubeV3::Video.new(
status: status,
snippet: snippet,
)
#service.insert_video(
'id,snippet,status',
video_object,
notify_subscribers: true,
content_type: 'video/webm',
options: { authorization: #client }
)
Help needed to make it work. Authentication is not working
Related
I am creating a rails application to post invoices to quickbooks I am using this gem quickbooks-ruby every time when I try to authenticate with quickbooks It gives this error OAuth::Problem parameter_rejected below is my code.
quickbook.rb (initialiser)
::QB_OAUTH_CONSUMER = OAuth::Consumer.new(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, {
:site => "https://oauth.intuit.com",
:request_token_path => "/oauth/v1/get_request_token",
:authorize_url => "https://appcenter.intuit.com/Connect/Begin",
:access_token_path => "/oauth/v1/get_access_token"
})
Authenticate method in controller
def authenticate_quickbooks
callback = api_webhooks_quickbook_oauth_callback_path
token = QB_OAUTH_CONSUMER.get_request_token(:oauth_callback => callback)
session[:qb_request_token] = token
redirect_to("https://appcenter.intuit.com/Connect/Begin?oauth_token=#{token.token}") and return
end
callback
def quickbooks_oauth_callback
at = session[:qb_request_token].get_access_token(:oauth_verifier => params[:oauth_verifier])
token = at.token
secret = at.secret
realm_id = params['realmId']
end
Problem solved. My quickbooks app was using oAuth2 and the gem has different method of authentication for oAuth1 and oAuth2.
below is the code (for OAuth2):
quickbook.rb (initialiser)
oauth_params = {
:site => "https://appcenter.intuit.com/connect/oauth2",
:authorize_url => "https://appcenter.intuit.com/connect/oauth2",
:token_url => "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer"
}
::QB_OAUTH2_CONSUMER = OAuth2::Client.new(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, oauth_params)
Quickbooks.sandbox_mode = true
Authenticate method in controller
redirect_uri = "http://localhost:3000#{quickbooks_authenticate_callback_path}"
grant_url = ::QB_OAUTH2_CONSUMER.auth_code.authorize_url(:redirect_uri => redirect_uri, :response_type => "code", :state => SecureRandom.hex(12), :scope => "com.intuit.quickbooks.accounting")
redirect_to grant_url
callback
redirect_uri = oauth_callback_quickbooks_url
if resp = ::QB_OAUTH2_CONSUMER.auth_code.get_token(params[:code], :redirect_uri => redirect_uri)
where oauth_callback_quickbooks_url = application callback which is also defined in quickbooks app
please note that you also have to include oauth2 gem
What does this error signify?
Missing token endpoint URI. highlighted at #account_summaries
def analytics
client = Signet::OAuth2::Client.new(access_token: session[:access_token]['access_token'])
service = Google::Apis::AnalyticsV3::AnalyticsService.new
service.authorization = client
#account_summaries = service.list_account_summaries
end
I tried searching everywhere, but can't understand in context of Google Analytics API what does this even mean?
Technically, the code should just work, but for some reason its not playing nice. Where exactly is it going wrong?
Full code
class WelcomeController < ApplicationController
def redirect
client = Signet::OAuth2::Client.new({
client_id: 'APP ID',
client_secret: 'APP SECRET',
authorization_uri: 'https://accounts.google.com/o/oauth2/auth',
scope: Google::Apis::AnalyticsV3::AUTH_ANALYTICS_READONLY,
redirect_uri: url_for(:action => :oauth2callback)
additional_parameters: { access_type: :offline, approval_prompt: :force }
})
redirect_to client.authorization_uri.to_s
end
def oauth2callback
client = Signet::OAuth2::Client.new({
client_id: 'APP ID',
client_secret: 'APP SECRET',
token_credential_uri: 'https://accounts.google.com/o/oauth2/token',
redirect_uri: url_for(:action => :oauth2callback),
code: params[:code]
})
response = client.fetch_access_token!
session[:access_token] = response['access_token']
redirect_to url_for(:action => :analytics)
end
def analytics
client = Signet::OAuth2::Client.new(access_token: session[:access_token]['access_token'])
service = Google::Apis::AnalyticsV3::AnalyticsService.new
service.authorization = client
#account_summaries = service.list_account_summaries
end
end
I want to use Yahoo Fantasy sport API in my web application, For that I am using OAuth for Yahoo login. I have consumer key and secret key and i passed the keys successfully, When I run the following code. It redirects to Yahoo login, It asks permission for accessing the user's credentials. If i give AGREE the page Redirects to https://api.login.yahoo.com/oauth/v2/request_auth and It shows the Verifying code. If i press the close button in verification code page, it's not callback to my URL.
#ts=Time.now.to_i
#callback_url = "http://localhost:3000/callback"
#nonce = SecureRandom.hex()
consumer = OAuth::Consumer.new("my consumerkey","secret key",
{ :site => 'https://api.login.yahoo.com',
:http_method => :post,
:scheme => :header,
:oauth_nonce => #nonce,
:request_token_path => '/oauth/v2/get_request_token',
:authorize_path => '/oauth/v2/request_auth',
:access_token_path => '/oauth/v2/get_token',
:oauth_callback => "http://localhost:3000/callback",
:oauth_timestamp => Time.now.to_i,
:oauth_signature_method => "HMAC-SHA-1",
:oauth_version => "1.0",
:oauth_callback_confirmed => true,
})
request_token = consumer.get_request_token
session[:request_token]=request_token
redirect_to request_token.authorize_url
access_token=request_token.get_access_token
access = ActiveSupport::JSON.decode(access_token.to_json)
if !(access.present?)
#response = "Response failed"
else
#response = access
end
Can you please tell me What changes to be made to get the callback for to get access_token.
I think you got confused while getting callback. change your code as follows, You will surely get access token to make Yahoo API call.
##access_token = nil
##request_token = nil
def get_request_token
##consumer = OAuth::Consumer.new('consumer key',
'secret key',
{
:site => 'https://api.login.yahoo.com',
:scheme => :query_string,
:http_method => :get,
:request_token_path => '/oauth/v2/get_request_token',
:access_token_path => '/oauth/v2/get_token',
:authorize_path => '/oauth/v2/request_auth'
})
##request_token = ##consumer.get_request_token( { :oauth_callback => 'http://localhost:3000/callback' } )
session[:request_token]=##request_token
redirect_to ##request_token.authorize_url
#redirect_to ##request_token.authorize_url( { :oauth_callback => 'http://localhost:3000/success' } )
end
def callback
request_token = ActiveSupport::JSON.decode(##request_token.to_json)
if !(request_token.present?)
$request_token_value = "Response failed"
else
$request_token_value = request_token
end
# access_token = ##request_token.get_access_token({:oauth_verifier=>params[:oauth_verifier],:oauth_token=>params[:oauth_token]})
##access_token = ##request_token.get_access_token(:oauth_verifier=>params[:oauth_verifier])
access_json = ActiveSupport::JSON.decode(##access_token.to_json)
puts "****************************"
puts $access_json
puts "****************************"
end
In my controller I have the following actions
def twitter
client = TwitterOAuth::Client.new(
:consumer_key => ENV['TWITTER_KEY'],
:consumer_secret => ENV['TWITTER_SECRET']
)
request_token = client.request_token(oauth_callback: "http://myawesomeapp.herokuapp.com/create_users/get_twitter_info")
redirect_to "https://www.twitter.com/oauth/authenticate?oauth_token=#{request_token.params[:oauth_token]}"
end
def get_twitter_info
redirect_to "https://www.twitter.com/oauth/access_token?oauth_verifier=#{params[:oauth_verifier]}&oauth_token=#{params[:oauth_token]}"
end
def results
end
In my Twitter application settings, I've set Access to Read Only and checkmarked Allow this application to be used to Sign in with Twitter. Why is it returning
Invalid Request Token
when it hits the https://twitter.com/oauth/access_token page?
In Main function You write Simply this code
redirect_url = "http://myawesomeapp.herokuapp.com/create_users/get_twitter_info"
url = URI.parse(URI.encode(redirect_url.strip))
consumer_key=consumer key
consumer_secret=consumer secret
oauth = OAuth::Consumer.new(consumer_key, consumer_secret,
{ :site => "http://api.twitter.com" })
request_token = oauth.get_request_token(:oauth_callback => url)
session[:twitter_token] = request_token.token
session[:twitter_secret] = request_token.secret
and in
get_twitter_info
function you write
consumer_key=consumer key
consumer_secret=consumer secret
oauth = OAuth::Consumer.new(consumer_key,consumer_secret,
{ :site => "http://api.twitter.com" })
request_token = OAuth::RequestToken.new(oauth, session[:twitter_token], session[:twitter_secret])
#access_token = request_token.get_access_token(
:oauth_verifier => params[:oauth_verifier])
But Keep in mind in your twitter application setting you mention callback url is
http://myawesomeapp.herokuapp.com/create_users/get_twitter_info
I'm so confused by OAuth and Google. It took me forever to get the refresh_token to create a new access_token. Then to find out the refresh_token expires too?? What is the point of that!!!??
All I need to do is persist a valid access_token for use with legato.
Here is what I manually enter into my terminal to retrieve an OAUTH code:
client = OAuth2::Client.new('GA_CLIENT_ID', 'GA_SECRET_KEY', {
:authorize_url => 'https://accounts.google.com/o/oauth2/auth',
:token_url => 'https://accounts.google.com/o/oauth2/token'
})
client.auth_code.authorize_url({
:scope => 'https://www.googleapis.com/auth/analytics.readonly',
:redirect_uri => 'http://localhost',
:access_type => 'offline',
:approval_prompt=> 'force'
})
Then I manually enter the outputted url to in my browser. I export the returned OAUTH code as to an env variable and get the access token:
access_token = client.auth_code.get_token(ENV['GA_OAUTH_CODE'], :redirect_uri => 'http://localhost')
Then I can access the access_token and refresh_token:
begin
api_client_obj = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {:site => 'https://www.googleapis.com'})
api_access_token_obj = OAuth2::AccessToken.new(api_client_obj, ENV['GA_OAUTH_ACCESS_TOKEN'])
self.user = Legato::User.new(api_access_token_obj)
self.user.web_properties.first # this tests the access code and throws an exception if invalid
rescue Exception => e
refresh_token
end
end
def refresh_token
refresh_client_obj = OAuth2::Client.new(ENV['GA_CLIENT_ID'], ENV['GA_SECRET_KEY'], {
:authorize_url => 'https://accounts.google.com/o/oauth2/auth',
:token_url => 'https://accounts.google.com/o/oauth2/token'
})
refresh_access_token_obj = OAuth2::AccessToken.new(refresh_client_obj, ENV['GA_OAUTH_ACCESS_TOKEN'], {refresh_token: ENV['GA_OAUTH_REFRESH_TOKEN']})
refresh_access_token_obj.refresh!
self.user = Legato::User.new(refresh_access_token_obj)
end
After an hour, my tokens expire and I have to manually start the process over again from the browser! How can I replicate this in code??
Here you go, made a little something just for you :)
It's a simple implementation, specifically to ease the pain of renewing tokens.
Just be sure to:
Put in your own APP_ID and APP_SECRET.
Either only save your refresh_token and call refresh_token() every time before you use it, or use refresh_token_if_needed() every time, and re-save the token and expires_at (preferred obviously , since you'll only refresh when needed).
Let me know how it worked out.
.
require 'gmail'
require 'gmail_xoauth'
require 'httparty'
class GmailManager
APP_ID = "DDDDDDDDDDDD-SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS.apps.googleusercontent.com"
APP_SECRET = "SSSSSS-SSSSSSSSSSSSSSSSS"
def refresh_token(refresh_token)
Rails.logger.info "[GmailManager:refresh_token] refreshing using this refresh_token: #{refresh_token}"
# Refresh auth token from google_oauth2 and then requeue the job.
options = {
body: {
client_id: APP_ID,
client_secret: APP_SECRET,
refresh_token: refresh_token,
grant_type: 'refresh_token'
},
headers: {
'Content-Type' => 'application/x-www-form-urlencoded'
}
}
response = HTTParty.post('https://accounts.google.com/o/oauth2/token', options)
if response.code == 200
token = response.parsed_response['access_token']
expires_in = DateTime.now + response.parsed_response['expires_in'].seconds
Rails.logger.info "Success! token: #{token}, expires_in #{expires_in}"
return token, expires_in
else
Rails.logger.error "Unable to refresh google_oauth2 authentication token."
Rails.logger.error "Refresh token response body: #{response.body}"
end
return nil, nil
end
def refresh_token_if_needed(token, expires_on, refresh_token)
if token.nil? or expires_on.nil? or Time.now >= expires_on
Rails.logger.info "[GmailManager:refresh_token_if_needed] refreshing using this refresh_token: #{refresh_token}"
new_token, new_expires_on = self.refresh_token(refresh_token)
if !new_token.nil? and !new_expires_on.nil?
return new_token, new_expires_on
end
else
Rails.logger.info "[GmailManager:refresh_token_if_needed] not refreshing. using this token: #{token}"
end
return token, expires_on
end
end