Oauth2 google-api-ruby-client: How to set Approval Prompt to Auto? - ruby

Question:
How to set the Approval Prompt to Auto? It defaults to 'approval_prompt=force'
Code:
I am setting up the client like this.
#client = Google::APIClient.new(
:authorization => :oauth_2,
:host => 'www.googleapis.com',
:http_adapter => HTTPAdapter::NetHTTPAdapter.new
)
#client.authorization.client_id = 'xxxx.apps.googleusercontent.com'
#client.authorization.client_secret = 'xxxx'
Context: Google OAuth2
Client Library: google-api-ruby-client
Reference: Same question for the php client :
Google+ OAuth API store and retrieve tokens after first login and authorization
Signet Documentation. I can't find the approval_prompt setter
http://signet.rubyforge.org/api/Signet/OAuth2/Client.html

This is how I solved the problem.
I wrote a separate helper method that will generate the Google OAuth URI
def build_auth_uri
return #client.authorization.authorization_uri(
:approval_prompt => :auto
).to_s
end
Next, instead of referring to Google OAuth URI directly in my view, I called the helper.
That did the trick.

This is how I solved the problem:
In /app/views/devise/shared/_links.haml (it's similar for _links.erb):
- if devise_mapping.omniauthable?
- resource_class.omniauth_providers.each do |provider|
- if provider == :google_oauth2
= link_to "Sign in with Google", omniauth_authorize_path(resource_name, provider, approval_prompt: :auto)
- else
= link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider)
%br/
EDIT: Even easier: Add this to your devise.rb or omniauth.rb initializer (in /config/initializers):
provider :google_oauth2, ENV["GOOGLE_KEY"], ENV["GOOGLE_SECRET"], {
approval_prompt: "auto"
}
Check the documentation here for more info.

Related

OctoKit Ruby Authentication

I'm sure that this is a simple error, but I'm interested in writing a program that collects information on all of my github repositories. While this seems simple enough to do with Octokit, I've run into issues associated with authenticating my session.
client = Octokit::Client.new \
:login => 'MY_USER_NAME',
:password => 'MY_PASSWORD'
puts client
user = client.user("MY_USER_NAME", :headers => { "PERSONAL_ACCESS_TOKEN_NAME" => "TOKEN" })
puts user
Unfortunately this results in the following:
GET https://api.github.com/users/mccoleman75225: 401 - Must specify two-factor authentication OTP code. // See: https://developer.github.com/v3/auth#working-with-two-factor-authentication (Octokit::OneTimePasswordRequired)
How does someone go about authenticating their session?
As of January 2022, you can create a PAT (Personal Access Token) in your GitHub Developer Settings and use that to connect through the Octokit client like so:
client = Octokit::Client.new(:access_token => "<Your Personal Access Token>")
user = client.user
user.login
# => "monacat"
Here's a step-by-step guide on how to create a PAT. Try to select the correct permissions when creating your token or you'll get back a 403 error with a message explaining the missing scope. You can always go back and edit your scopes later though.
Sources:
Octokit.rb — Authentication
GitHub API Authentication - Personal Access Tokens
Looks like you have 2 Factor Authentication enabled on your account so you'll need to add your 2FA token:
client = Octokit::Client.new \
:login => 'defunkt',
:password => 'c0d3b4ssssss!'
client.create_authorization(:scopes => ["user"], :note => "Name of token",
:headers => { "X-GitHub-OTP" => "<your 2FA token>" })
# => <your new oauth token>
See documentation

Proxy in ruby gem "twitter_oauth"

My test environment for my Ruby (Sinatra + twitter_oauth) project is behind a proxy.
In the documentation, I read how to use the twitter_oauth gem with a proxy. But there the author says:
First you need to authorize the Twitter user via OAuth directly via the Twitter API (this part cannot be proxied)
But unfortunately, on this step I receive an proxy error when testing locally.
Is there any possibility to proxy this?
client = TwitterOAuth::Client.new(
:consumer_key => 'YOUR_APP_CONSUMER_KEY',
:consumer_secret => 'YOURA_APP_CONSUMER_SECRET'
)
request_token = client.request_token(:oauth_callback => 'YOUR_CALLBACK_URL')
Thanks in advance!!
No, but OAuth can be skipped if a check for local environment is wrapped around the authentication:
def localhost
client = "Test"
request_token = "Me"
def webhost
client = TwitterOAuth::Client.new(
:consumer_key => 'YOUR_APP_CONSUMER_KEY',
:consumer_secret => 'YOURA_APP_CONSUMER_SECRET'
)
request_token = client.request_token(:oauth_callback => 'YOUR_CALLBACK_URL')

RestClient basic auth with # in username

I have a problem with a daemon accessing a REST api.
The access requires basic authentication. The username and password are fixed and can not be changed.
The problem seems to be, that the username looks like this: #ws+R4nd0mS7r1n
I access the API like this:
resource = RestClient::Resource.new( "#{base_url}/failover/#{failover_ip}", { :user => user_name, :password => user_password})
response = resource.get
This gets me an bad URI error:
bad URI(absolute but no path): https://#ws+R4nd0mS7r1n:RaNdOmPaSsWoRd#robot-ws.your-server.de/failover/11.11.11.11
When I itentionally remove the # from the username it works, but I get a NOT Authenticated error.
Is there a way to pass a username or password containing # to restclient?
Passing the complete URI manually to a .get does not work either.
I don't get the same error. What version of rest-client do you have installed?
You may simply be able to update the version to fix your problem (I tested with version 1.6.7 of the gem)
Alternatively, this works around the URI failure by directly writing to the Authorization header (which is where this data ends up anyway):
require 'base64'
auth = 'Basic ' + Base64.encode64( "#{user_name}:#{user_password}" ).chomp
resource = RestClient::Resource.new( "#{base_url}/failover/#{failover_ip}", { :headers => { 'Authorization' => auth } } )
resource.get

Error working with Typhoreus and SeoMoz API

I am working with the SEOMoz API using the Typhoreus gem. To authenticate(Signed Authentication) with the API, I use the following code:
url = "http://lsapi.seomoz.com/linkscape/url-metrics/"+website.url.strip+"?Cols=103079231520"
response = Typhoeus::Request.get(url, :username => "member-xxxxxxx", :password => "abcxyzwhatever")
To which I get the error: Ethon::Errors::InvalidOption: The option: username is invalid.
Please try userpwd instead of username.
If I change the username to userpwd, it asks to change password to userpwd as well.
Where am I going wrong?
The api changed a bit, that should work:
Typhoeus::Request.get(url, :userpwd => "member-xxxxxxx:abcxyzwhatever")

omniauth oauth tokens for gmail are invalid

I'm trying to get an oauth token I can use with gmail_xauth (ruby gem)
to look at a user's mail. I first registered my app with google and
then set up devise to request access to mail:
config.omniauth :google, 'key', 'secret', :scope => 'https://mail.google.com/mail/feed/atom/'
I then go through the outh/openid flow and google prompts me to
approve access to gmail, redirecting me back to the app with a a token
and secret in the omniuth credentials & my Google account lists my app
as authorized to access my data. So far so good.
Now, when I take those credentials and try to use them with
gmail_xoauth like so:
require 'gmail_xoauth'
imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs =
nil, verify = false)
imap.authenticate('XOAUTH', '...#gmail.com',
:consumer_key => 'key,
:consumer_secret => 'secret',
:token => 'omniauth_returned_token',
:token_secret => 'omniauth_returned_secret'
)
I get an error "Net::IMAP::NoResponseError: Invalid credentials
(Failure)".
Interestingly, following the gmail_xoauth README to generate a token
with an same consumer using a python script it does work.
This works for me:
config.omniauth :google, 'anonymous', 'anonymous', :scope => 'https://mail.google.com/'
I'm using the gmail gem, so to connect it looks like this:
gmail = Gmail.connect(:xoauth, auth.uid,
:token => auth.token,
:secret => auth.secret,
:consumer_key => 'anonymous',
:consumer_secret => 'anonymous'
)
I'm passing an authentication object in, but you'll be getting it from the env variable env["omniauth.auth"]. I'm using anonymous/anonymous for the key/secret since I haven't registered my domain with google, but I believe you can here. It'll still work with anonymous/anonymous, but Google will just warn the user.
Google's OAuth1 protocol is now deprecated and many gems have not yet updated to use their OAuth2 protocol. Here is a working example of fetching email from Google using their OAuth2 protocol. This example uses the mail, gmail_xoauth, omniauth, and omniauth-google-oauth2 gems.
You will also need to register your app in Google's API console in order to get your API tokens.
# in an initializer:
ENV['GOOGLE_KEY'] = 'yourkey'
ENV['GOOGLE_SECRET'] = 'yoursecret'
Rails.application.config.middleware.use OmniAuth::Builder do
provider :google_oauth2, ENV['GOOGLE_KEY'], ENV['GOOGLE_SECRET'], {
scope: 'https://mail.google.com/,https://www.googleapis.com/auth/userinfo.email'
}
end
# ...after handling login with OmniAuth...
# in your script
email = auth_hash[:info][:email]
access_token = auth_hash[:credentials][:token]
imap = Net::IMAP.new('imap.gmail.com', 993, usessl = true, certs = nil, verify = false)
imap.authenticate('XOAUTH2', email, access_token)
imap.select('INBOX')
imap.search(['ALL']).each do |message_id|
msg = imap.fetch(message_id,'RFC822')[0].attr['RFC822']
mail = Mail.read_from_string msg
puts mail.subject
puts mail.text_part.body.to_s
puts mail.html_part.body.to_s
end

Resources