-
-
Save cigzigwon/4ff99b48438d5be85633bdecfd2c2e06 to your computer and use it in GitHub Desktop.
@oauth_creds [ | |
realm: "#{@acct_id}", | |
oauth_consumer_key: "<CONSUMER_KEY>", | |
oauth_consumer_secret: "<CONSUMER_SECRET>", | |
oauth_token: "<TOKEN>", | |
oauth_token_secret: "<TOKEN_SECRET>", | |
oauth_signature_method: "HMAC-SHA256", | |
oauth_version: "1.0" | |
] | |
def forge_oauth_head(method, url, qs \\ []) do | |
timestamp = DateTime.utc_now() |> DateTime.to_unix() |> Integer.to_string() | |
seed = :crypto.strong_rand_bytes(16) |> Base.encode16() | |
nonce = :crypto.hash(:md5, seed) |> Base.encode16(case: :lower) |> String.slice(0..12) | |
head = | |
(@oauth_creds ++ [oauth_timestamp: timestamp, oauth_nonce: nonce]) | |
|> Enum.reject(fn {key, _} -> | |
[:oauth_consumer_secret, :oauth_token_secret] |> Enum.member?(key) | |
end) | |
|> Enum.reduce([], fn {key, value}, acc -> | |
acc ++ ["#{key}=\"#{value |> URI.encode_www_form()}\""] | |
end) | |
|> Enum.join(",") | |
{"Authorization", | |
"OAuth #{head}" <> | |
",oauth_signature=\"" <> | |
forge_sign(method <> "&" <> (url |> URI.encode_www_form()), timestamp, nonce, qs) <> "\""} | |
end | |
def forge_sign(head, timestamp, nonce, qs) do | |
params = | |
(@oauth_creds ++ [oauth_timestamp: timestamp, oauth_nonce: nonce] ++ qs) | |
|> Enum.reject(fn {key, _} -> | |
[:realm, :oauth_consumer_secret, :oauth_token_secret] |> Enum.member?(key) | |
end) | |
|> Enum.sort_by(fn {key, val} -> | |
{key, val} | |
end) | |
|> Enum.reduce([], fn {key, value}, acc -> | |
acc ++ ["#{key}=#{value |> URI.encode(&URI.char_unreserved?(&1))}"] | |
end) | |
|> Enum.join("&") | |
|> URI.encode_www_form() | |
key = | |
(@oauth_creds |> Keyword.fetch!(:oauth_consumer_secret)) <> | |
"&" <> (@oauth_creds |> Keyword.fetch!(:oauth_token_secret)) | |
:crypto.hmac(:sha256, key, head <> "&" <> params) | |
|> Base.encode64(case: :lower) | |
|> URI.encode_www_form() | |
end | |
Hi @cigzigwon... really appreciate your posting this code. I wrestled with it for a few hours and couldn't get it to work then figured out since I am hitting the SuiteQL endpoint with a POST I just had to call forge_oauth_head
with "POST" and make sure the content-type
and prefer
headers were set.
I probably could have gotten the Oauther PR to work the same way but your code allows me to remove that dependency and it works great. Thanks!!
@tmepple Great! It was specifically design3d for NetSuite and with that being said I'm just going to fork this thing and add some additional control. As you have found it only supplies an auth header. NS Rest Web Service is based on OAS2 so it has a hypermedia spec. Understandung those will save you 5ime and alsways ask a question . I'm gonna fork to add the control we need to work with newer APIs that use TBA
Caller:
HTTPoison.get( url, [ forge_oauth_head("GET", url, p) ], params: p, timeout: timeout )