How to get the bearer token from a webhook Ruby on Rails - ruby-on-rails

I receive datas from webhook and I try to get the Authorization Bearer token that is in the headers
I tried :
data = JSON.parse(response.body)
puts "TOKEN " + data['csrf-token']['content']
Also :
if headers['Authorization'].present?
puts " HEADER " + headers['Authorization'].split(' ').last
else
puts "ERROR"
end
-> I have the ERROR
And :
data = response.body
puts "TOKEN " + data['csrf-token']['content']
-> It returns nil
Turns out that the solution was :
bearer_token = request.headers["Authorization"]
Thanks all for your help !

data = JSON.parse(response.body)
#⇒ JSON::ParserError (767: unexpected token ...
The library you use to get the response seems to parse the response on its own, you don’t need to call JSON#parse again. The below should work.
data = response.body
puts "TOKEN " + data['csrf-token']['content']

.....
I think you can get Authorization Bearer token like :-
if headers['Authorization'].present?
return headers['Authorization'].split(' ').last
else
errors.add(:token, 'Missing token')
end

Related

Howt to authenticate linkedin rest api?

I'm trying to make an web app using linkedin rest api.
I'm following these instructions. I have done step-1.
I have created an application on Linkedin. I got Client ID and Client Secret for that app.
I'm stuck with step-2. How do I get USER_TOKEN and USER_SECRET for my app? Any help would be appreciated.
Try following this. For Python linkedin lib.
consumer = oauth.Consumer(consumer_key,consumer_secret)
client = oauth.Client(consumer)
request_token_url = 'https://api.linkedin.com/uas/oauth/requestToken'
resp, content = client.request(request_token_url, "POST")
if resp['status'] != '200':
raise Exception("Invalid response %s." % resp['status'])
print content
request_token = dict(urlparse.parse_qsl(content))
print "Requesr Token:", "\n"
print "- oauth_token = %s" % request_token['oauth_token'], "\n"
print "- oauth_token_secret = %s" % request_token['oauth_token_secret'], "\n"
authorize_url = 'https://api.linkedin.com/uas/oauth/authorize'
print "Go to the following link in your browser:", "\n"
print "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token']), "\n"
accepted = 'n'
while accepted.lower() == 'n':
accepted = raw_input('Have you authorized me? (y/n) ')
oauth_verifier = raw_input('What is the PIN? ')
access_token_url = 'https://api.linkedin.com/uas/oauth/accessToken'
token = oauth.Token(request_token['oauth_token'], request_token['oauth_token_secret'])
token.set_verifier(oauth_verifier)
client = oauth.Client(consumer, token)
resp, content = client.request(access_token_url, "POST")
access_token = dict(urlparse.parse_qsl(content))
print "Access Token:", "\n"
print "- oauth_token = %s" % access_token['oauth_token'], "\n"
print "- oauth_token_secret = %s" % access_token['oauth_token_secret']
print "You may now access protected resources using the access tokens above."

Using HMAC SHA256 in Ruby

I'm trying to apply HMAC-SHA256 for generate a key for an Rest API.
I'm doing something like this:
def generateTransactionHash(stringToHash)
key = '123'
data = 'stringToHash'
digest = OpenSSL::Digest.new('sha256')
hmac = OpenSSL::HMAC.digest(digest, key, data)
puts hmac
end
The output of this is always this: (if I put '12345' as parameter or 'HUSYED815X', I do get the same)
ۯw/{o���p�T����:��a�h��E|q
The API is not working because of this... Can some one help me with that?
According to the documentation OpenSSL::HMAC.digest
Returns the authentication code an instance represents as a binary string.
If you have a problem using that maybe you need a hex encoded form provided by OpenSSL::HMAC.hexdigest
Example
key = 'key'
data = 'The quick brown fox jumps over the lazy dog'
digest = OpenSSL::Digest.new('sha256')
OpenSSL::HMAC.digest(digest, key, data)
#=> "\xF7\xBC\x83\xF40S\x84$\xB12\x98\xE6\xAAo\xB1C\xEFMY\xA1IF\x17Y\x97G\x9D\xBC-\x1A<\xD8"
OpenSSL::HMAC.hexdigest(digest, key, data)
#=> "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"
Try This:
hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), key, data)
def make_payment(user)
#key= SecureRandom.hex(10)
#puts #key
#secret_key = #key
puts " this is the public key #{#secret_key}"
#access_key= generate_key
puts " this is the access key #{#access_key}"
#name= #user.name
puts "#{#name}"
#time= Time.now.in_time_zone("Nairobi")
puts "This is the time request sent #{#time}"
#server_key = SecureRandom.base64
puts "This is the server key #{#server_key}"
#data = 'This request is being made from Learnida for users to make a payment'
#digest = OpenSSL::Digest.new('sha256')
uri = URI.parse("https://learnida.com")
#hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), #secret_key, #access_key)
puts "This is the HMAC #{#hmac}"
req = Net::HTTP::Get.new(uri)
req['Authorization'] = "TM-HMAC-SHA256 key=#{#access_key} ts=#{#time} sign=#{#hmac}"
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
#hmacdigest= OpenSSL::HMAC.digest(#digest, #server_key, #data)
puts" This is the HMAC:SHA-256: #{#hmacdigest}"
#puts res.body
#=> "\xF7\xBC\x83\xF40S\x84$\xB12\x98\xE6\xAAo\xB1C\xEFMY\xA1IF\x17Y\x97G\x9D\xBC-\x1A<\xD8"
#sslkey= OpenSSL::HMAC.hexdigest(#digest, #server_key, #data)
puts #sslkey
In my case (Ticketmatic) I had to create the HMAC like above and add an Authorization header to the request with the HMAC in it.
hmac = OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), secret_key, access_key + name + time)
req = Net::HTTP::Get.new(uri)
req['Authorization'] = "TM-HMAC-SHA256 key=#{access_key} ts=#{time} sign=#{hmac}"
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
You can find a full gist here
And a blogpost with more explantion here

Pretty print webservice response on ruby

I have to call a webservice but I don't know the format of the response. In any case (xml, json or html) I have to pretty print the response.
For example, if it is a xml I have to indent and show it properly. Same thing if it is a json. I have two problems here:
Detecting the format
Apply a format depending on the type.
I think that (1) is the most challenging problem.
Any help?
As several of the comments have suggested, the http header will contain the content type.
net/http has methods for this: http://ruby-doc.org/stdlib-2.0.0/libdoc/net/http/rdoc/Net/HTTP.html#method-i-head
require 'net/http'
require 'json'
require 'rexml/document'
response = nil
Net::HTTP.start('www.google.com', 80) {|http|
response = http.get('/index.html')
}
header = response['content-type'].split(';').first # => "text/html"
body = response.read_body
then you can conditionally operate:
if header == "text/html"
puts response.read_body
elsif header == "application/json"
puts JSON.pretty_generate(JSON.parse(body))
elsif header == "text/xml"
xml = REXML::Document.new body
out = ""
xml.write(out, 1)
puts out
end
Most of this was pulled form other SO posts:
pretty JSON: How can I "pretty" format my JSON output in Ruby on Rails?
pretty XML: How to beautify xml code in rails application
This is the code that I finally used:
raw_response = response.body
response_html = ''
if response.header['Content-Type'].include? 'application/json'
tokens = CodeRay.scan(raw_response, :json)
response_html = tokens.div
elsif response.header['Content-Type'].include? 'application/xml'
tokens = CodeRay.scan(raw_response, :xml)
response_html = tokens.div
elsif response.header['Content-Type'].include? 'text/html'
tokens = CodeRay.scan(raw_response, :html)
response_html = tokens.div
else
response_html = '<div>' + raw_response + '</div>'
end
It's using the coderay gem.

Alllow for "bad" urls in in Rails

I have a simple script which checks for bad url's:
def self.check_prod_links
require 'net/http'
results = []
Product.find_each(:conditions =>{:published => 1}) do |product|
url = product.url
id = product.id
uri = URI(url)
begin
response = Net::HTTP.get_response(uri)
rescue
begin
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
rescue
begin
response = Net::HTTP.get_response("http://" + uri)
rescue => e
p "Problem getting url: #{url} Error Message: #{e.message}"
end
end
end
p "Checking URL = #{url}. ID = #{id}. Response Code = #{response.code}"
unless response.code.to_i == 200
product.update_attribute(:published, 0)
results << product
end
end
return results
end
How can I allow incorrectly formatted urls eg: hkbfksrhf.google.com to not crash the script with the following error:
getaddrinfo: nodename nor servname provided, or not known
I just want the task to run till the end, and print any/all errors that are not a 200 and 301 http response.
Thanks!
Is open-uri an option? It throws an exception when 404s or 500s (or other HTTP exceptions) are encountered, in addition to SocketErrors, which allows you to clean up your code a bit
def self.check_prod_links
require 'open-uri'
results = []
Product.where(:published => 1).each do |product|
url = product.url
id = product.id
failed = true
begin
open URI(url)
failed = false
rescue OpenURI::HTTPError => e
error_message = e.message
response_message = "Response Code = #{e.io.status[0]}"
rescue SocketError => e
error_message = e.message
response_message = "Host unreachable"
rescue => e
error_message = e.message
response_message = "Unknown error"
end
if failed
Rails.logger.error "Problem getting url: #{url} Error Message: #{error_message}"
Rails.logger.error "Checking URL = #{url}. ID = #{id}. #{response_message}".
product.update_attribute(:published, 0).
results << product
end
end
results
end

How do I do Rails Basic Authorization with RestClient?

I am trying to post a request to a REST service (HP ALM 11 REST API fwiw) using rest-client and keep getting the Unauthorized response. Could be I am not following the docs right but also I am not sure I am doing the headers properly. So far my googling for RestClient has been fruitless. Any help would be appreciated:
Code:
#alm_url = "http://alm_url/qcbin/"
#user_name = "username"
#user_password = "password"
authentication_url = #alm_url + "rest/is-authenticate"
resource = RestClient::Resource.new authentication_url
resource.head :Authorization => Base64.encode64(#user_name) + ":" + Base64.encode64(#user_password)
response = resource.get
#response = RestClient.get authentication_url, :authorization => #username, #user_password
Rails.logger.debug response.inspect
Based on this SO question I also tried the following without success:
#alm_url = "http://alm_url/qcbin/"
#user_name = "username"
#user_password = "password"
authentication_url = #alm_url + "rest/is-authenticate"
resource = RestClient::Resource.new authentication_url, {:user => #user_name, :password => #user_password}
response = resource.get
#response = RestClient.get authentication_url, :authorization => #username, #user_password
Rails.logger.debug response.inspect
Documentation:
Client sends a valid Basic Authentication header to the authentication
point.
GET /qcbin/authentication-point/authenticate Authorization: Basic
ABCDE123
Server validates the Basic authentication headers, creates a new
LW-SSO token and returns it as LWSSO_COOKIE_KEY.
Okay... so first it helps if I go to the right URL:
authentication_url = #alm_url + "rest/is-authenticate"
Which should read:
authentication_url = #alm_url + "authentication-point/authenticate"
Secondly, it helps if I read the docs for RestClient rather than just look at the readme. The example under Instance Method Details helped a lot.
My code now looks like:
#alm_url = "http://alm_url/qcbin/"
#user_name = "username"
#user_password = "password"
authentication_url = #alm_url + "authentication-point/authenticate"
resource = RestClient::Resource.new(authentication_url, #user_name, #user_password)
response = resource.get
Rails.logger.debug response.inspect
EDIT:
Wow I really over-thought this. I could have gone with:
response = RestClient.get "http://#{#user_name}:#{#user_password}#alm_url/qcbin/authentication-point/authenticate"

Resources