Сбой аутентификации Powershell OAuth 1.0 с использованием HMA C -SHA1 - PullRequest
0 голосов
/ 02 апреля 2020

Я пытаюсь написать скрипт Powershell, чтобы получить данные из веб-API, который использует «одноногий» (это означает, что у вас есть только ключ потребителя (имя пользователя) и секрет потребителя (пароль)) OAuth1. 0 аутентификации. Я изучил документы OAuth1.0 (https://oauth.net/core/1.0/) и затем создал следующий скрипт:

$response                   = $null
$url                        = 'https://api.holidaypictures.com/api/v1.0/0'

$oauth_consumer_key         = 'myusername@domain.com'
$oauth_consumer_secret      = 'SuperSecretHash'
$oauth_nonce                = -join ((65..90) + (97..122) | Get-Random -Count 12 | % {[char]$_})
$oauth_signature_method     = 'HMAC-SHA1'
$oauth_timestamp            = [int64](([datetime]::UtcNow)-(get-date "1/1/1970")).TotalSeconds
$oauth_token                = '' # Don't have this because 'one-legged' authentication
$oauth_token_secret         = '' # Don't have this because 'one-legged' authentication
$oauth_version              = '1.0'

$method                     = 'POST'

$base_string  = 'oauth_consumer_key=' + $oauth_consumer_key
$base_string += '&oauth_nonce=' + $oauth_nonce
$base_string += '&oauth_signature_method=' + $oauth_signature_method
$base_string += '&oauth_timestamp=' + $oauth_timestamp
$base_string += '&oauth_token=' + $oauth_token
$base_string += '&oauth_version=' + $oauth_version

$signature_base_string      = $method + '&' + [System.Web.HttpUtility]::UrlEncode($url) + '&' + [System.Web.HttpUtility]::UrlEncode($base_string)

$key = $oauth_consumer_secret + '&' + $oauth_token_secret
$hmacsha1 = new-object System.Security.Cryptography.HMACSHA1;
$hmacsha1.Key = [System.Text.Encoding]::ASCII.GetBytes($key);
$oauth_signature = [System.Convert]::ToBase64String($hmacsha1.ComputeHash([System.Text.Encoding]::ASCII.GetBytes($signature_base_string)));
$oauth_signature
$oauth_signature = [System.Web.HttpUtility]::UrlEncode($oauth_signature)

$oauth_signature

$auth  = 'OAuth '
$auth += 'oauth_consumer_key="' + $oauth_consumer_key + '",'
$auth += 'oauth_nonce="' + $oauth_nonce + '",'
$auth += 'oauth_signature="' + $oauth_signature + '",'
$auth += 'oauth_signature_method="' + $oauth_signature_method + '",'
$auth += 'oauth_timestamp="' + $oauth_timestamp + '",'
$auth += 'oauth_token="' + $oauth_token + '",'
$auth += 'oauth_version="' + $oauth_version + '"'

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Content-Type", "application/json")
$headers.Add("Authorization", $auth)
$body = "{`n    `"pageSize`": 10,`n `"sort`": [`n       {`n         `"key`": `"info.date`",`n           `"direction`": -1`n         `n      }`n ],`n    `"idSelection`": [],`n  `"query`": []`n}"

$response = Invoke-RestMethod -Method $method -Headers $headers -body $body -Uri $url

При запуске этого кода возникает следующая ошибка:

Invoke-RestMethod : {"status":401,"message":"Could not authorize request","scope":"SECURITY","details":null}
At line:47 char:13
+ $response = Invoke-RestMethod -Method $method -Headers $headers -body ...
+             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (Method: POST, Reque\u2026application/json
}:HttpRequestMessage) [Invoke-RestMethod], HttpResponseException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Другими словами: он не может аутентифицироваться. Есть ли кто-нибудь, кто может помочь мне в этом? Будем признательны!

Кстати, об API MoreApp.com ... Не знаю, поможет ли это.

...