RestClient basic auth with # in username - ruby

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

Related

Ruby gRPC server authentication SSL/TLS and a custom header with token

I need to connect to a server with authentication and a custom header.
The official gRPC docs show how to do it in Python but not in Ruby:
https://grpc.io/docs/guides/auth/#with-server-authentication-ssltls-and-a-custom-header-with-token
How can this be achieved in ruby ? There doesn't seem to be a metadata call credentials method.
I have tried the following but I'm getting Permission Denied.
channel_creds = GRPC::Core::ChannelCredentials.new()
auth_proc = proc { { 'authorization' => 'Plain ****' } }
call_creds = GRPC::Core::CallCredentials.new(auth_proc)
combined_creds = channel_creds.compose(call_creds)
#stub = Stub.new('host:port', combined_creds)
Nevermind, it was an error because of protection from the server that needed to be disabled, the above code works fine.

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

401 unauthorized from Twitter API with oauth gem in Ruby

This is my first experience working with Twitter API's.
I am using the following tools:
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-linux]
gem 'oauth'
oauth (0.5.1)
oauth2 (1.1.0)
omniauth-oauth2 (1.4.0)
I obtained a key and secret from Twitter.
I copied and pasted from the example on Twitter for Ruby.
=begin
code taken directly from the example at
https://dev.twitter.com/oauth/overview/single-user
=end
require 'oauth'
consumer_key, \
consumer_secret = [
'CONSUMER_KEY',
'CONSUMER_SECRET'
].map { |key| ENV[key] }
raise "Some key undefined." unless [consumer_key, consumer_secret].all?
# Exchange your oauth_token and oauth_token_secret for an AccessToken instance.
def prepare_access_token(oauth_token, oauth_token_secret)
consumer = OAuth::Consumer.new("APIKey", "APISecret", { :site => "https://api.twitter.com", :scheme => :header })
# now create the access token object from passed values
token_hash = { :oauth_token => oauth_token, :oauth_token_secret => oauth_token_secret }
access_token = OAuth::AccessToken.from_hash(consumer, token_hash )
return access_token
end
# Exchange our oauth_token and oauth_token secret for the AccessToken instance.
access_token = prepare_access_token(consumer_key, consumer_secret)
p access_token
# use the access token as an agent to get the home timeline
response = access_token.request(:get, "https://api.twitter.com/1.1/statuses/home_timeline.json")
p response
=begin
|| #<OAuth::AccessToken:0x000000021ed938
#token="redacted", #secret="redacted",
#consumer=#<OAuth::Consumer:0x000000021edb68
#key="APIKey",
#secret="APISecret", #options={:signature_method=>"HMAC-SHA1",
:request_token_path=>"/oauth/request_token",
:authorize_path=>"/oauth/authorize",
:access_token_path=>"/oauth/access_token",
:proxy=>nil, :scheme=>:header,
:http_method=>:post, :oauth_version=>"1.0",
:site=>"https://api.twitter.com"}>,
#params={:oauth_token=>"redacted", :oauth_token_secret=>"redacted"}>
|| #<Net::HTTPUnauthorized 401 Authorization Required readbody=true>
=end
What I tried:
Getting a new key and secret.
Result:
Net::HTTPUnauthorized 401 Authorization Required readbody=true
Synchronized my server's time because many Stack Overflow posts mentioned that a 401 is returned if the server time varies beyond a certain point. I installed ntp.
suggestions from this list
set the Callback URL in Twitter settings: http://127.0.0.1:3000/auth/twitter/callback
API Console Tool on Twitter. After authenticating with my Twitter account https://api.twitter.com/1.1/statuses/home_timeline.json returns
HTTP/1.1 200 OK
along with expected data.
checked to see if Twitter API operating normally
Suggestions of where to go from here appreciated.
UPDATE OAuth Tool on Twitter Developer returns the expected result with a curl execution:
curl --get 'https://api.twitter.com/1.1/statuses/home_timeline.json' --header 'Authorization: OAuth oauth_consumer_key="redacted", oauth_nonce="redacted", oauth_signature="redacted", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1463742270", oauth_token="redacted", oauth_version="1.0"' --verbose
Expected data is returned.
[{"created_at":"Fri May 20 11:05:21 +0000
2016","id":733614584754515968,"id_str":
"733614584754515968","text":"Three Skills Every New Programmer Should
Learn https://t. co/1p9AxO5JPg via
#sitepointdotcom","truncated":false,"entities":{"hashtags":[],"symbols"
(truncated)…
On this line, you should replace "APIKey" and "APISecret" with what you pulled from the CONSUMER_* environment variables.
consumer = OAuth::Consumer.new("APIKey", "APISecret", { :site => "https://api.twitter.com", :scheme => :header })
The example code from Twitter works fine for me. The wrong consumer keys will give you 401 for sure.

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')

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")

Resources