'How to use Ruby net/http for post with headers?

I'm trying to make the following request, but it's not returning a token like I would expect. If I try in postman with the same body and headers, it works just fine and I can get a token. But in Ruby the token is missing and the body doesn't look like what I would expect

uri = URI.parse("https://api.kroger.com/v1/connect/oauth2/token")
    req = Net::HTTP::Post.new(uri, initheader = {
      'Authorization' =>'Basic token',
      'Content-Type' => 'application/x-www-form-urlencoded'
    })
    req.set_form_data('grant_type' => 'client_credentials', 'scope' => 'product.compact')
    
    res = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => true) do |http|
      http.request(req)
    end


Solution 1:[1]

Your Authorization header is incomplete. You are passing in 'Basic token' but according to the Kroger API docs it should include a base-64 encoded CLIENT_ID and CLIENT_SECRET separated by a single :.

encoded_token = Base64.strict_encode64("#{CLIENT_ID}:#{CLIENT_SECRET}")
req = Net::HTTP::Post.new(uri, initheader = {
  'Authorization' => "Basic #{encoded_token}",
  'Content-Type' => 'application/x-www-form-urlencoded'
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 clarked