INVOKE-RESTMethod Issue (401)

This topic contains 2 replies, has 2 voices, and was last updated by  D 1 week, 4 days ago.

  • Author
    Posts
  • #102209

    D
    Participant

    Hi Guys I am trying to call this Api, but I am struggling to get the output and getting 401 error. tried on Rest Client app and it worked but not been able to get it working on powershell.
    The Curl code I got when it worked on Rest Client is as follows:-

    curl -X POST -k -H 'Content-Type: application/json' -H 'Authorization: OAuth oauth_signature_method="HMAC-SHA256", oauth_nonce="UPsZ9", oauth_timestamp="1242546", oauth_consumer_key="random", oauth_token="random", oauth_version="1.0", oauth_signature="random"' -i 'https://random.net/messaging_history/api/account/37007926/agent-view/summary' --data '{}'
    
    

    I am just trying to get it working using powershell.

    The powershell script I am using is getting Oauthentication correctly but failing at INVOKE-RESTMETHOD. I have tried searching Oauth 1.0 examples online but there isn't much information available. So this code is more or less borrowed from here and there andthats why looks like two codes as follows:-

    [Reflection.Assembly]::LoadWithPartialName("System.Security")
    [Reflection.Assembly]::LoadWithPartialName("System.Net")
    
    $status = [System.Uri]::EscapeDataString("{}");
    $oauth_consumer_key = "random";
    $oauth_consumer_secret = "random";
    $oauth_token = "random";
    $oauth_token_secret = "random";
    $oauth_nonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString()));
    $ts = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime();
    $oauth_timestamp = [System.Convert]::ToInt64($ts.TotalSeconds).ToString();
    
    $signature = "POST&";
    $signature += [System.Uri]::EscapeDataString("https://random") + "&";
    $signature += [System.Uri]::EscapeDataString("oauth_consumer_key=" + $oauth_consumer_key + "&");
    $signature += [System.Uri]::EscapeDataString("oauth_nonce=" + $oauth_nonce + "&"); 
    $signature += [System.Uri]::EscapeDataString("oauth_signature_method=HMAC-SHA1&");
    $signature += [System.Uri]::EscapeDataString("oauth_timestamp=" + $oauth_timestamp + "&");
    $signature += [System.Uri]::EscapeDataString("oauth_token=" + $oauth_token + "&");
    $signature += [System.Uri]::EscapeDataString("oauth_version=1.0&");
    $signature += [System.Uri]::EscapeDataString("status=" + $status);
    
    $signature_key = [System.Uri]::EscapeDataString($oauth_consumer_secret) + "&" + [System.Uri]::EscapeDataString($oauth_token_secret);
    
    $hmacsha1 = new-object System.Security.Cryptography.HMACSHA1;
    $hmacsha1.Key = [System.Text.Encoding]::ASCII.GetBytes($signature_key);
    $oauth_signature = [System.Convert]::ToBase64String($hmacsha1.ComputeHash([System.Text.Encoding]::ASCII.GetBytes($signature)));
    
    $oauth_authorization = 'OAuth ';
    $oauth_authorization += 'oauth_consumer_key="' + [System.Uri]::EscapeDataString($oauth_consumer_key) + '",';
    $oauth_authorization += 'oauth_nonce="' + [System.Uri]::EscapeDataString($oauth_nonce) + '",';
    $oauth_authorization += 'oauth_signature="' + [System.Uri]::EscapeDataString($oauth_signature) + '",';
    $oauth_authorization += 'oauth_signature_method="HMAC-SHA1",'
    $oauth_authorization += 'oauth_timestamp="' + [System.Uri]::EscapeDataString($oauth_timestamp) + '",'
    $oauth_authorization += 'oauth_token="' + [System.Uri]::EscapeDataString($oauth_token) + '",';
    $oauth_authorization += 'oauth_version="1.0"';
    
    $url = 'https://random'
    
    
    
    [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create("https://random");
    $request.Method = "POST";
    $request.Headers.Add("Authorization", $oauth_authorization);
    $request.ContentType = "application/json";
    $result = $request.GetRequestStream();
    $headers=@{"Authorization"= $oauth_authorization}
    
    
    $algorithm = "{`"alg`":`"none`"}`n"
    
    
    $algorithmBase64 = [Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($algorithm))
    $body = {} -f 'eyJhbGciOiJub25lIn0K',$accessCode
    
    $params = @{
        ContentType = 'application/x-www-form-urlencoded'
        Headers = @{"Authorization"= $oauth_authorization}
        Body = {} -f $algorithmBase64
        Method = 'Post'
        URI = $url
    }
    
    
    $d= Invoke-RestMethod -Uri $url -Method POST -Headers $headers -body $body
    
    # Invoke-RestMethod @params
    
    
  • #102281

    Don Jones
    Keymaster

    Yeah, this is some real Frankencode :).

    [System.Net.HttpWebRequest] $request = [System.Net.WebRequest]::Create("https://random");
    $request.Method = "POST";
    $request.Headers.Add("Authorization", $oauth_authorization);
    $request.ContentType = "application/json";
    $result = $request.GetRequestStream();
    $headers=@{"Authorization"= $oauth_authorization}
    

    That bit should be executing the request. I mean, really, up until Invoke-RestMethod, you're doing a pretty straightforward set of .NET stuff. It might be easier to just keep doing that, versus switching back to the PowerShell command. StackOverflow.com might be a good source for .NET examples.

    There's a bunch here I don't get – I'm not sure if you do, but if you do, you can maybe help me understand. For example:

    $params = @{
        ContentType = 'application/x-www-form-urlencoded'
        Headers = @{"Authorization"= $oauth_authorization}
        Body = {} -f $algorithmBase64
        Method = 'Post'
        URI = $url
    }
    
    
    $d= Invoke-RestMethod -Uri $url -Method POST -Headers $headers -body $body
    

    Why did you create $params and then not use it? It seems like you've pasted a bunch of different techniques together, but they're not all going to work together. You're probably going to need to clean up the code and just pick one approach to go with.

  • #102286

    D
    Participant

    Sorry, I was trying different approaches but wasn't able to get anything working. Finally got it working, because I was trying to use twitter's example to call the API and there was line for status update and I thought it was for the body of API call. This was causing issues with 'oauth_nouce'. Anyway here is the right solution if anyone needs it.

     
     
    [CmdletBinding(DefaultParameterSetName = 'None')] 
        [OutputType('System.Management.Automation.PSCustomObject')]
    
    
    PARAM( [Parameter()] [string] $oauth_consumer_key, [Parameter()]  [string] $oauth_consumer_secret,  [Parameter()] [string] $oauth_token, [Parameter()] [string] $oauth_token_secret, [Parameter()] [string] $url,[Parameter()][string] $location)
    
    $oauth_nonce = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes([System.DateTime]::Now.Ticks.ToString()));
    $ts = [System.DateTime]::UtcNow - [System.DateTime]::ParseExact("01/01/1970", "dd/MM/yyyy", $null).ToUniversalTime();
    $oauth_timestamp = [System.Convert]::ToInt64($ts.TotalSeconds).ToString();
    
    $signature = "POST&";
    $signature += [System.Uri]::EscapeDataString( $url) + "&";
    $signature += [System.Uri]::EscapeDataString("oauth_consumer_key=" + $oauth_consumer_key + "&");
    $signature += [System.Uri]::EscapeDataString("oauth_nonce=" + $oauth_nonce + "&"); 
    $signature += [System.Uri]::EscapeDataString("oauth_signature_method=HMAC-SHA1&");
    $signature += [System.Uri]::EscapeDataString("oauth_timestamp=" + $oauth_timestamp + "&");
    $signature += [System.Uri]::EscapeDataString("oauth_token=" + $oauth_token + "&");
    $signature += [System.Uri]::EscapeDataString("oauth_version=1.0");
     
    $signature_key = [System.Uri]::EscapeDataString($oauth_consumer_secret) + "&" + [System.Uri]::EscapeDataString($oauth_token_secret);
     
    $hmacsha1 = new-object System.Security.Cryptography.HMACSHA1;
    $hmacsha1.Key = [System.Text.Encoding]::ASCII.GetBytes($signature_key);
    $oauth_signature = [System.Convert]::ToBase64String($hmacsha1.ComputeHash([System.Text.Encoding]::ASCII.GetBytes($signature)));
     
    $oauth_authorization = 'OAuth ';
    $oauth_authorization += 'oauth_consumer_key="' + [System.Uri]::EscapeDataString($oauth_consumer_key) + '",';
    $oauth_authorization += 'oauth_nonce="' + [System.Uri]::EscapeDataString($oauth_nonce) + '",';
    $oauth_authorization += 'oauth_signature="' + [System.Uri]::EscapeDataString($oauth_signature) + '",';
    $oauth_authorization += 'oauth_signature_method="HMAC-SHA1",'
    $oauth_authorization += 'oauth_timestamp="' + [System.Uri]::EscapeDataString($oauth_timestamp) + '",'
    $oauth_authorization += 'oauth_token="' + [System.Uri]::EscapeDataString($oauth_token) + '",';
    $oauth_authorization += 'oauth_version="1.0"';
     
    
    $headers=@{'Authorization'= $oauth_authorization}
     $body='{
         "interactive": true,
         "ended": true,
         "start": {
           "from": 1527811200000,
           "to": 1528416000000
         }
       }' 
     
      
    
     Invoke-RestMethod -Method post -Uri $url -Body $body -Headers $headers -ContentType 'application/json' -OutFile $location 
    

You must be logged in to reply to this topic.