简体   繁体   中英

curl to Ruby request for connecting to wheniwork

Back story

I've spent a few days on the Ruby gem for wheniwork , and it's been a nightmare. To make a long story short, the gem had a dependency of an older version of activesupport and I basically forked their repo and made a compatible version for my ruby project. I was able to create a new gem and attempted to use it, but I was getting the following json message:

{"error"=>"User login required for this resource.", "code"=>1000}

The username, password, and api key were set. What I basically need to do is access our account on wheniwork, and retrieve data.

This is an example using the curl command

curl https://api.wheniwork.com/2/login \
  --data '{"username":"user@example.com","password":"*******"}' \
  -H "W-Key: iworksoharditsnotfunny"

Essentially, I would get some kind of return object from wheniwork that would contain the token. I'd use this token for future requests to the wheniwork site.

To (Ruby)

A new attempt to translate this to Ruby

require 'net/http'


data = {'credentials' => {'username' => 'XXXXX@XXXXX.com','password' => 'XXXXX', 'W-Key' => '111111111XXXXX'}}

uri = URI.parse("https://api.wheniwork.com/2/login/")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
request.add_field('Content-Type', 'application/json')
request.body = data.to_json
response = http.request(request)

Result:

#<Net::HTTPUnauthorized 401 Unauthorized readbody=true>

If you have any idea or clue (or basically anything that would help me here), I would appreciate it beyond words. Thanks!

Got it!! The major issue(s) were that the api key and (username+password) combo are two separate pieces.

I was so close the entire time, but here it is:

  data = {'username' => 'XXXX@XXXXXXX.com','password' => 'XXXXX'}

  uri = URI.parse("https://api.wheniwork.com/2/login/")
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  request = Net::HTTP::Post.new(uri.path)
  request.add_field('W-Key', 'XXXXXXXXXXXXX')
  request.body = data.to_json
  response = http.request(request)

  puts JSON.parse(response.body)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM