Last active
December 30, 2022 06:39
-
-
Save jacoyutorius/609c2b7c348794bccfeb59ca97a9bdef to your computer and use it in GitHub Desktop.
OAuth1.0a認証用ヘッダーを生成する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'openssl' | |
require 'cgi' | |
require 'base64' | |
# see https://developer.twitter.com/ja/docs/authentication/oauth-1-0a/creating-a-signature | |
module Oauth1_0a | |
class Authorization | |
attr_accessor :http_method, :url, :consumer_key, :consumer_secret, :token, :token_secret, :nonce, :timestamp | |
def initialize(http_method:, url:, consumer_key:, consumer_secret:, token:, token_secret:) | |
@http_method = http_method | |
@url = url | |
@consumer_key = consumer_key | |
@consumer_secret = consumer_secret | |
@token = token | |
@token_secret = token_secret | |
@nonce = OpenSSL::Random.random_bytes(16).unpack('H*')[0] | |
@timestamp = Time.now.to_i.to_s | |
end | |
def signature | |
Base64.encode64( | |
OpenSSL::HMAC.digest(OpenSSL::Digest::SHA1.new, signature_key, signature_base) | |
) | |
.chomp | |
.gsub(/\n/, '') | |
end | |
def authorization_header | |
dst = { | |
'oauth_consumer_key' => consumer_key, | |
'oauth_nonce' => nonce, | |
'oauth_signature' => signature, | |
'oauth_signature_method' => 'HMAC-SHA1', | |
'oauth_timestamp' => timestamp, | |
'oauth_token' => token, | |
'oauth_version' => '1.0' | |
}.collect { |k, v| %(#{k}="#{CGI.escape(v)}") }.join(',') | |
"OAuth #{dst}" | |
end | |
private | |
def signature_base | |
params = { | |
'oauth_consumer_key' => consumer_key, | |
'oauth_nonce' => nonce, | |
'oauth_signature_method' => 'HMAC-SHA1', | |
'oauth_timestamp' => timestamp, | |
'oauth_token' => token, | |
'oauth_version' => '1.0' | |
}.collect {|p| p.collect { |v| CGI.escape(v) } } | |
.sort | |
.collect { |p| p.join('=') } | |
.join('&') | |
[ | |
http_method, | |
CGI.escape(url), | |
CGI.escape(params) | |
].join('&') | |
end | |
def signature_key | |
CGI.escape(consumer_secret) + '&' + CGI.escape(token_secret) | |
end | |
end | |
end | |
pp Oauth1_0a::Authorization.new( | |
http_method: 'POST', | |
url: 'https://api.twitter.com/2/tweets', | |
consumer_key: '', | |
consumer_secret: '', | |
token: '', | |
token_secret: '').authorization_header if __FILE__ == $0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment