Ruby Oauth Gem HMAC-SHA1 401 Invalid Signature

2019-08-01 19:21发布

I'm using rest-client with oauth, the oauth headers are getting generated, but the hmac-sha1 signature is invalid.

The server doesn't accept signature encoding, returns 401 oauth_problem signature_invalid.

oauth_signature="9aOk2oM2%2FczpqHBJ95MhcF%2Bp6XU%3D",  
oauth_signature_method="HMAC-SHA1"

Running in Postman with "Encode OAuth signature" un-selected works fine. Postman gives same 401 invalid signature when this option is turned on.

Is this encoding the problem, is there a similar option for oauth gem and how can I set it?

require 'rubygems'

require 'oauth'
require 'rest-client'

# auth keys read in from file
base_uri = 'http://dockerized-magento.local'
base_path = 'api/rest'
base_url = base_uri + '/' + base_path + '/customers'   # the fix

 @consumer=OAuth::Consumer.new auth['consumer_key'],
                               auth['consumer_secret'],
                               {:site => base_url }      # the fix
 # this was the error
 #                              {:site=> base_uri + base_path}

# Create the access_token for all traffic
access_token = OAuth::AccessToken.new(@consumer, 
                                      auth['token'], auth['token_secret'])

RestClient.add_before_execution_proc do |req, params|
  access_token.sign! req
end

response = RestClient::Request.execute(method: :get, url: url, 
                                       timeout: 60, 
                                       headers: {'Cache-Control' => 'no-cache'})

rest-client 2.0 with oauth gem 0.5.1., ruby 2.2.2, not using ruby-on-rails

1条回答
趁早两清
2楼-- · 2019-08-01 20:00

The problem was I incorrectly set the base url. I saw this: Creating a signature and

The base URL is the URL to which the request is directed, minus any query string or hash parameters. It is important to use the correct protocol here, so make sure that the “https://” or “http://” portion of the URL matches the actual request sent to the API. I adjusted my base_url accordingly

base_uri = 'http://dockerized-magento.local'
base_path = 'api/rest'

base_url = base_uri + '/' + base_path + '/customers'

and changed

     @consumer=OAuth::Consumer.new auth['consumer_key'],
                           auth['consumer_secret'],
                           {:site=> base_url}

I am updating the code above for clarity.

查看更多
登录 后发表回答