HTTParty get request using Basic Auth - ruby-on-rails

I am trying to make get request to this address https://unicom24.ru/api/partners/requests/v1/locality/
I am using httparty gem. I need to use basic http Auth.
I got my auth key and do request like this:
headers = {'Authorization' => 'Basic bMyAuthKeydv4K'}
HTTParty.get(
"https://unicom24.ru/api/partners/requests/v1/locality/",
:headers => headers
)
And I get a reply:
#response=#<Net::HTTPUnauthorized 401 Unauthorized readbody=true>
unallowable email or password.
What do I do?

HTTParty basic auth
auth = {username: 'user', password: 'pass'}
result = HTTParty.get(
"https://unicom24.ru/api/partners/requests/v1/locality/",
basic_auth: auth
)

Related

Rails Net::HTTP.post_form API returns 500 Internal Error although it returns correct response through PostMan

I am trying to get the API Token from this api.
https://docs.bigmarker.com/#login
Basically below is the API format and it works with PostMan as well
curl -i -X POST --data "email=youremail#email.com&password=yourpassword" https://www.bigmarker.com/api/v1/members/login
I didn't specify any Headers, Just use the POST form data with email & password.
And this is my rails code.
require 'net/http'
require 'net/https'
uri = URI("https://www.bigmarker.com/api/v1/members/login")
res = Net::HTTP.post_form(uri, {'email' => email, 'passowrd' => password})
But it returns HTTP 500 Error.
#<Net::HTTPInternalServerError 500 Internal Server Error readbody=true>
Any idea?
Thanks
My mistake.
There was a spelling error.
res = Net::HTTP.post_form(uri, {'email' => email, 'passowrd' => password})
'passowrd' should be 'password'

Newsletter2go ruby API client authorisation with get_token method

Good day!
Can you please give me an example of authentication request with ruby newsletetr2go API client.
I can't figure it out.
I can connect to API using direct requests like RestClient.post "#{link}/oauth/v2/token", credentials, default_header
In credentials I use my username, password and grant_type, converted to json format
In default header I use content_type: 'application/json' and authorization: "Basic #{Base64.strict_encode64(ENV['NEWSLETTER2GO_AUTH_KEY'])}"
And it works fine. But when I try to use newsletter2go get_token method all I receive is "BAD REQUEST" error.
I'm using initializer to configure SwaggerClient like this:
SwaggerClient.configure do |config|
# Configure OAuth2 access token for authorization: OAuth
config.password = ENV['NEWSLETTER2GO_PASSWORD']
config.username = ENV['NEWSLETTER2GO_USERNAME']
config.api_key = ENV['NEWSLETTER2GO_AUTH_KEY']
end
After that I use newsletter2go api method call
SwaggerClient::AuthorizationApi.new.get_token("https://nl2go.com/jwt")
Seems everything is correct, but error "BAD REQUEST" happens all the time.
I followed the instructions, install swagger_client with ruby extentions in github, and newsletter2go methods are now available from my rails environment.
If I grab access_token manually and add it to my initializer, then do some requests like SwaggerClient::ListApi.new.get_lists it gives me a proper response with status 200 and list_ids
But SwaggerClient::AuthorizationApi.new.get_token("https://nl2go.com/jwt") does not work and this is the issue.
Any help would be very appreciated!
I figured out the reason why Newsletter2Go API ruby client does not grab api_key value. For some reason it's hardcoded to setup basic auth token which stands from username and password packed.
Here is code from
module SwaggerClient
class Configuration
# Gets Basic Auth token string
def basic_auth_token
'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n")
end
# Returns Auth Settings hash for api client.
def auth_settings
{
'OAuth' =>
{
type: 'oauth2',
in: 'header',
key: 'Authorization',
value: "Bearer #{access_token}"
},
'Basic' =>
{
type: 'basic',
in: 'header',
key: 'Authorization',
value: basic_auth_token
},
}
end

Rails RestClient pass token in header fails

I do this curl in Terminal which works excellent:
$ curl https://myurl.com/api/v1/orders/53e0ae7f6630361c46060000 -H "Authorization: Token xxxxxxxxxxxxxxxxxxxxxx"
Output is json.
Now I want to access the json string via my rails app. I have tried RestClient to do this, but somehow I always get a 401 unauthorized error. I believe the token gets not send correctly via header. I have tried the following:
RestClient.get 'https://myurl.com/api/v1/orders/53e0ae7f6630361c46060000', {token: 'xxxxxxxxxxxxxxxxxxxxxx'}
and
RestClient.get 'https://myurl.com/api/v1/orders/53e0ae7f6630361c46060000', :params => {:token => 'xxxxxxxxxxxxxxxxxxxxxx'}
with no success. Maybe I use a wrong syntax for sending the token in the header?
Doku is here http://rubydoc.info/github/rest-client/rest-client - I could not find any mistakes.
# GET request with modified headers
RestClient.get 'http://example.com/resource', {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}
# POST request with modified headers
RestClient.post 'http://example.com/resource', {:foo => 'bar', :baz => 'qux'}, {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}
# DELETE request with modified headers
RestClient.delete 'http://example.com/resource', {:Authorization => 'Bearer cT0febFoD5lxAlNAXHo6g'}
Source: https://github.com/rest-client/rest-client#headers

Ruby and Twitter: Getting Access Token from Request Token?

I am currently in Step 3 of the processing on getting an oauth token/secret from an user trying to login via Twitter. https://dev.twitter.com/docs/auth/implementing-sign-twitter
Step 3 tells me to send this request to the API, but I am stuck as to how to do so. I currently have BOTH the oauth_token and oauth_verifier, but how do I send this POST request to get the oauth_token, oauth_token_secret pair?
Is there a standard Oauth Ruby gem I can use to send this POST request? I see examples online where I pass an #accessToken object, but i do not have such an object available. I just have the oauth_token and oauth_verifier (as strings). Given these 2 things, how do I convert them to an oauth_token and oauth_token_secret?
POST /oauth/access_token HTTP/1.1
User-Agent: themattharris' HTTP Client
Host: api.twitter.com
Accept: */*
Authorization: OAuth oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w",
oauth_nonce="a9900fe68e2573b27a37f10fbad6a755",
oauth_signature="39cipBtIOHEEnybAR4sATQTpl2I%3D",
oauth_signature_method="HMAC-SHA1",
oauth_timestamp="1318467427",
oauth_token="NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0",
oauth_version="1.0"
Content-Length: 57
Content-Type: application/x-www-form-urlencoded
oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY
Try something like the following rails controller actions, using the twitter and oauth gems:
def redirect
consumer = OAuth::Consumer.new(CONSUMER_KEY, CONSUMER_SECRET, {
:site => "https://api.twitter.com",
:scheme => :header
})
request_token = consumer.get_request_token(:oauth_callback => CALLBACK_URL)
session[:twitter_request_token] = request_token
redirect_to request_token.authorize_url #=> "https://api.twitter.com/oauth/authorize?oauth_token=XYZ"
end
def callback
request_token = session[:twitter_request_token]
access_token = request_token.get_access_token(:oauth_verifier => params[:oauth_verifier])
client = Twitter::REST::Client.new(
:consumer_key => CONSUMER_KEY,
:consumer_secret => CONSUMER_SECRET,
:access_token => access_token.token,
:access_token_secret => access_token.secret
)
twitter_user = client.user
redirect_to root_url # or do something with the twitter_user
end
See also: http://barkingiguana.com/2009/10/13/twitter-oauth-authentication-using-ruby/
yes there is the Omniauth gem for authentication with Twitter. The documentation is straight forward.
I personally use Omniauth integrated with Devise and the Twitter gem to access Twitter - works very well.
Hope this helps,
Eugen
The common procedure is the following:
You shell to register your app on twitter development page.
Then set the proper Name, Description, and Website values up for your application.
App Name
App Description
http://your_app_domain.zone:3000/
Change Application Type is your app, by default it has read only access type.
Setup the callback URL for yuor application:
http://your_app_domain.zone:3000/auth/twitter/callback
Store the all keys, and secrets that are shewn on the OAuth tool twitter page:
Consumer key:
Consumer secret:
Access token:
Access token secret:
Setup route on your site with devise, or devise-like gem with the specified twitter keys, and secrets to enable authentication engine. The route list now shall include /auth/twitter path.
By going to http://your_app_domain.zone:3000/auth/twitter you will be redirected to twitter site, and dropped back to your site with passed oauth_token
But
You simple receive those keys, and secrets, and apply then in your app, avoiding the 6, and 7 points:
client = Twitter::REST::Client.new do |config|
config.consumer_key = "YOUR_CONSUMER_KEY"
config.consumer_secret = "YOUR_CONSUMER_SECRET"
config.access_token = "YOUR_ACCESS_TOKEN"
config.access_token_secret = "YOUR_ACCESS_SECRET"
end

POSTing in OAuth with client credentials with Doorkeeper

I've implemented a REST API and protected it with doorkeeper.
I've written a small client program to access it and it works fine using the resource owner credential flow.
Now I'm trying to implement a call using the client credentials flow. So I've followed the example in the link.
Everything works great when I'm using a GET request, but when I'm using a POST request, I'm getting a 401 Unauthorized. This is a call to a method that doesn't require a resource owner.
The only relevant thing I have in my API controller is:
doorkeeper_for :all
I haven't implemented any scopes or nothing of that kind (am I required to?).
My client code looks like this (exactly as in the example in github):
require 'rest-client'
require 'json'
client_id = 'my_client_id...'
client_secret = 'my_client_secret...'
response = RestClient.post 'http://localhost:3000/oauth/token', {
grant_type: 'client_credentials',
client_id: client_id,
client_secret: client_secret
}
token = JSON.parse(response)["access_token"]
# this line works great:
RestClient.get 'http://localhost:3000/api/v1/flights.json', { 'Authorization' => "Bearer #{token}" }
# this line always fails (401 Unauthorized):
RestClient.post 'http://localhost:3000/api/v1/flights.json', { 'Authorization' => "Bearer #{token}" }
Any idea what I may be doing wrong? Is there something special I should do in my application in order to enable the client credentials flow?
I figured it out. The problem was that I didn't use RestClient.post properly. The second parameter should be the payload and the third should be the header. It should be something like this:
RestClient.post 'http://localhost:3000/api/v1/flights.json', {}, { 'Authorization' => "Bearer #{token}" }

Resources