momo
#1
Hi all,
I’m trying to query GET /2/users/:id/followers endpoint with user.fields=created_at parameter using the OAuth 1.0a, but I keep getting 401 Unauthorized error.
https://api.twitter.com/2/users/12*******/followers?user.fields=created_at
if user.fields=created_at parameter is removed, it will be successful so I wonder it may be mistaken when I add a parameter.
Here is code in Ruby on Rails.
class GetFollowersService
TWITTER_API_DOMAIN = "https://api.twitter.com/2"
TWITTER_CONSUMER_SECRET = Rails.application.credentials.twitter[:secret_key]
def initialize(current_user, user_id)
@user = current_user
@user_id = user_id
end
def get_followers
uri = URI.parse(TWITTER_API_DOMAIN + "/users/#{@user_id}/followers")
params = {"user.fields": "created_at"}
uri.query = URI.encode_www_form(params)
request = Net::HTTP::Get.new(uri)
request.content_type = "application/json"
request["Authorization"] = authorization_value
options = { use_ssl: true }
response = Net::HTTP.start(uri.hostname, uri.port, options) do |http|
http.request(request)
end
puts response.body
end
private
def authorization_value
authorization_params = create_params.merge(
oauth_signature: generate_signature("GET", TWITTER_API_DOMAIN + "/users/#{@user_id}/followers?user.fields=created_at")
)
return "OAuth " + authorization_params.sort.to_h.map{|k, v| "#{k}=\"#{v}\"" }.join(",")
end
def create_params
@create_params ||= {
oauth_consumer_key: Rails.application.credentials.twitter[:key],
oauth_nonce: SecureRandom.alphanumeric,
oauth_signature_method: "HMAC-SHA1",
oauth_timestamp: Time.zone.now.to_i,
oauth_token: @user.authentication.access_token,
oauth_version: "1.0"
}
end
def oauth_values
values = create_params.sort.to_h.map {|k, v| "#{k}=#{v}" }.join("&")
ERB::Util.url_encode(values)
end
def generate_signature(method, url)
signature_data = [method, ERB::Util.url_encode(url), oauth_values].join("&")
signature_key = "#{ERB::Util.url_encode(TWITTER_CONSUMER_SECRET)}&#{ERB::Util.url_encode(@user.authentication.access_token_secret)}"
signature_binary = OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new, signature_key, signature_data)
return ERB::Util.url_encode(Base64.strict_encode64(signature_binary))
end
end
I look forward to hearing from you 
Thank you.
same situation. do you have fix it?
This should not be happening if using a library to handle oAuth - unless there’s a bug there, do you have a code sample?