Ruby Gem OAuth 1.0 无法在 Ruby 脚本中授权

问题描述 投票:0回答:1

我在我的脚本(非rails)中使用Ruby Oauth 1.0 库,该库调用需要授权的Flickr 3rd party API。我在获取请求令牌的授权时遇到问题。我不断地返回 401 Unauthorized。我的困惑源于 ruby 脚本中使用的回调、会话和重定向。这应该如何在本身不是网络服务器/rails 应用程序的常规 Ruby 脚本中工作?我已在 Postman 中手动进行身份验证,但为了获取授权验证程序,我必须打开浏览器并将回调粘贴为 URL,然后复制 URL 中显示的验证程序。

我认为,由于我没有在网站上进行身份验证,因此不需要回调、redirect_to 和会话。

有没有办法让它在我的脚本中工作而无需回调和重定向?

我尝试了以下方法并包含结果。

下面列出了我正在尝试做的事情的片段。

require 'oauth'
require 'byebug'

callback_url = "localhost URL"

# Create a new OAuth::Consumer instance by passing it a configuration hash:
consumer_key = "a2e299ac1d635a7c9f2d7c7b70588679"
consumer_secret = "235de478b9a078ae"

@oauth_consumer = OAuth::Consumer.new(consumer_key, consumer_secret, 
    {   :site => "https://flickr.com",
        # {   :site => "https://flickr.com/services",
        :scheme             => :header,
        :http_method        => :get,
        :request_token_path => "request_token URL",
        :access_token_path  => "access_token URL",
        :authorize_path     => "authorize URL",
        :body_hash_enabled  => false,
        :debug_output       => true
             })
@request_token = @oauth_consumer.get_request_token(oauth_callback: callback_url)
session = {}
session[:token] = @request_token
session[:token_secret] = @request_token
# redirect_to @request_token.authorize_url(oauth_callback: callback_url) # redirect_to not available in ruby script

puts "request token: #{session[:token]}"
puts "request token secret: #{session[:token_secret]}"
auth_str = @request_token.authorize_url(oauth_callback: callback_url)

# When user returns create an access_token
hash = { oauth_token: session[:token], oauth_token_secret: session[:token_secret] }
@request_token = OAuth::RequestToken.from_hash(@oauth_consumer, hash)

@access_token = @request_token.get_access_token
@recognitions = @access_token.get("login URL")
type here

我看到以下结果。

reading 28 bytes...
-> "oauth_problem=token_rejected"
read 28 bytes
Conn close
Traceback (most recent call last):
        2: from flickr_client.rb:38:in `<main>'
        1: from /Users/bhunsake/.rbenv/versions/2.7.7/lib/ruby/gems/2.7.0/gems/oauth-1.1.0/lib/oauth/tokens/request_token.rb:28:in `get_access_token'
/Users/bhunsake/.rbenv/versions/2.7.7/lib/ruby/gems/2.7.0/gems/oauth-1.1.0/lib/oauth/consumer.rb:268:in `token_request': 401 Unauthorized (OAuth::Unauthorized)

ruby oauth rubygems flickr
1个回答
0
投票

我找到了自己问题的简单答案。显然,当不需要登录验证时,Ruby Auth Consumer 对象会处理任何授权/身份验证。在这种情况下,使用 Flickr,我只需要添加消费者 (API) 密钥,如下所示。

require 'oauth'

consumer_key = "a2e299ac1d635a7c9f2d7c7b70588679"
consumer_secret = "235de478b9a078ae"
consumer = OAuth::Consumer.new(consumer_key, consumer_secret, 
    :site => "https://www.flickr.com/services")

response = consumer.request(:get, '/rest/?method=flickr.photos.getRecent&api_key=a2e299ac1d635a7c9f2d7c7b70588679&per_page=10&format=json&nojsoncallback=1', nil, {}, {})
puts response.body

© www.soinside.com 2019 - 2024. All rights reserved.