RestAPI authentication with PowerShell - powershell

I am trying to access the API of OpenProvider using PowerShell and I can't seem to get past Authentication.
The documentation for the API is here : https://support.openprovider.eu/hc/en-us/articles/360025683173-Getting-started-with-Openprovider-API
And my code looks like this:
$EndPoint = "https://api.openprovider.eu/v1beta/auth/login"
function Get-ConfHeaders
{
##Configure headers
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("ip","0.0.0.0")
$Headers.Add("username","myusername")
$Headers.Add("hash","APIpasswordhashgoeshere")
return $Headers
}
$header = Get-ConfHeaders
Invoke-RestMethod -Method Post -Uri $EndPoint -Headers $header
The response get is :
Invoke-RestMethod : The remote server returned an error: (500) Internal Server Error.
At line:36 char:1
+ Invoke-RestMethod -Method Post -Uri $EndPoint -Headers $header
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I am by no means an expert when it comes to API and any help would be appreciated.

Ok, I think the API documentation here leaves a lot to be desired.
You need to include the authentication in the body and it needs to be converted to JSON format. So the working code looks like this:-
$EndPoint = "https://api.openprovider.eu/v1beta/auth/login"
function Get-ConfHeaders
{
##Configure headers
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("ip","0.0.0.0")
$Headers.Add("username","username")
$Headers.Add("password","passwordhere")
return $Headers
}
$header = Get-ConfHeaders | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri $EndPoint -body $header -ContentType 'application/json'
Thanks for the help everyone.

Related

Webhook With PowerShell Discord

I am getting an error while using this code
$hookUrl = 'https://discord.com/api/webhooks/977171177120358412/U8T5Nv5BDCOL70IeXyPjA8Vlxo-4BB2b6QXhG0nAwD_gsw2AHXCSbbcjmiFvLlFFZD6I'
$content = #"
You can enter your message content here.
With a here-string, new lines are included as well!
Enjoy.
"#
$payload = [PSCustomObject]#{
content = $content
}
Invoke-RestMethod -Uri $hookUrl -Method Post -Body ($payload | ConvertTo-Json)
Invoke-RestMethod : {"message": "Cannot send an empty message", "code": 50006}
At line:17 char:1
+ Invoke-RestMethod -Uri $hookUrl -Method Post -Body ($payload | Conver ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I have no idea where I made a mistake, I would be glad if you could help me.
Invoke-restmethod -Uri $hookUrl -Method Post -Body ($payload | ConvertTo-Json) -Headers #{ "Content-Type" = "application/json" }
This seems to work

Unable to ingest JSON stream data to Azure Event Hub

I would like to post the JSON results which I am getting from an API endpoint to the Azure Event Hub $default consumer group but I am getting the below error:
Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.
At H:\Users\User1 - scripts\get_mel_streetparking_data.ps1:34 char:1
+ Invoke-RestMethod -Uri $URI -Method $method -Headers $headers -Body $res ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke- RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I wrote the below piece of powershell script where the following piece of get code runs fine:
$url = "https://data.melbourne.vic.gov.au/resource/vh2v-4nfs"
$apptoken = "abcdasdadaaf"
# Set header to accept JSON
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept","application/json")
$headers.Add("X-App-Token",$apptoken)
$results = Invoke-RestMethod -Uri $url -Method get -Headers $headers
but below piece of code fails with the above given error:
$method = "POST"
$URI = "https://[servicebusNamespace].servicebus.windows.net/[eventHubPath]/messages"
$signature = "SharedAccessSignature sr=[servicebusNamespace].servicebus.windows.net%2feventhub- streetparking&sig=%3dgZfDHEGN8lVEGgqu4N64TW70BLuSKARSKgMPeRByc%5d&se=604985&skn=RootManageSharedAccessKe"
# API headers
$headers = #{
"Authorization"=$signature;
"Content-Type"="application/json";
}
# create Request Body
#$body = "$results"
# execute the Azure REST API
Invoke-RestMethod -Uri $URI -Method $method -Headers $headers -Body $results
I generated SAS token with the help of the below code:
[Reflection.Assembly]::LoadWithPartialName("System.Web")| out-null
$URI="[servicebusNamespace].servicebus.windows.net/[eventHubPath]"
$Access_Policy_Name="RootManageSharedAccessKey"
$Access_Policy_Key="Root key value"
#Token expires now+3000
$Expires=([DateTimeOffset]::Now.ToUnixTimeSeconds())+3000
$SignatureString=[System.Web.HttpUtility]::UrlEncode($URI)+ "`n" + [string]$Expires
$HMAC = New-Object System.Security.Cryptography.HMACSHA256
$HMAC.key = [Text.Encoding]::ASCII.GetBytes($Access_Policy_Key)
$Signature = $HMAC.ComputeHash([Text.Encoding]::ASCII.GetBytes($SignatureString))
$Signature = [Convert]::ToBase64String($Signature)
$SASToken = "SharedAccessSignature sr=" + [System.Web.HttpUtility]::UrlEncode($URI) + "&sig=" + [System.Web.HttpUtility]::UrlEncode($Signature) + "&se=" + $Expires + "&skn=" + $Access_Policy_Name
$SASToken
Please help me why am I seeing unauthorized error
It was my bad that I did not replace the below values before the SAS token generation.
$Access_Policy_Name="RootManageSharedAccessKey"
$Access_Policy_Key="Root key value"

POST method in powershell gives 405 error

I have a POST method that works fine in Postman but I can't get it working in powershell.
The client id and client secret are setup in AWS cognito.
I am using basic authentication to retrieve the access token.
Below is my code,
$encodedlogin="MNBvbmZfYWsxUTRocG1qOG5zOGZqZ8xvN646a1plMDNsMTZjY6xucTA5MzVkOGg2aGdlaG1mdXAxaHZkMmlxaXY0PKOdM3BcxNBtPLs5"
$authorisation = "Basic " + $encodedlogin
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization",$authorisation)
$headers.Add("Accept","application/json")
$headers.Add("Content-Type","application/json")
$headers.Add("ResponseType","id_token")
$body = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$body.Add("grant_type","client_credentials")
$body.Add("scope","cybergate-gateway-resources/cybertron.fullaccess")
$uri = "https://cybergate.auth.eu-west-2.amazoncognito.com/oauth2/token"
$response = Invoke-WebRequest -Uri $uri -Headers $headers -body $body -Method Post -ContentType "application/json"
The error as follows,
Invoke-WebRequest : The remote server returned an error: (405) Method Not Allowed.
At C:\CyberGate\src\CyberGate.API\Scripts\Deploy\CyberGate.ps1:33 char:17
+ ... $response = Invoke-WebRequest -Uri $uri -Headers $headers -body $body ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
Any ideas?
Thanks

Powershell v5.1 Invoke-RestMethod Error Parsing Body

I'm a beginner with Powershell who's trying to send a PUT request to Microsoft Azure to create an Application Insights log query. I'm able to get this working in Postman, but not in a powershell script. This is the error that I'm getting when running the script:
Invoke-RestMethod : {"code":"Unexpected character encountered while parsing value: S. Path '', line 0, position 0.","message":"Unexpected character encountered while parsing value: S. Path '', line 0, position 0.","innererror":{"diagnosticcontext":"f2843c54-dad7-49b5-92ab-e1dadd40e145","time":"2020-07-24T19:59:45.7979293Z"}}
At C:\Users\thophan\source\Update-AiLogQueries.ps1:58 char:9
+ Invoke-RestMethod -Method Put -Uri $uri -Header $header -Body ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
From looking at the Microsoft documentation, it looks like it's supposed to be able to take in a hashtable for the body, and I'm quite certain my syntax looks exactly the same as the one from the exameple, so I'm not sure what's going on. Below is an excerpt from my script:
$scope = "shared"
$header = #{
"Authorization" = "Bearer $token"
}
$uri = "https://management.azure.com/subscriptions/$subscriptionId/resourceGroups/$rgName/providers/microsoft.insights/components/$aiName/analyticsItems/item?api-version=2020-02-02-preview"
$difference = Compare-Object -ReferenceObject $localQueryList.value -DifferenceObject $response
if ($difference -ne $null)
{
$difference.ForEach(
{
$body = #{
Scope = $scope
Type = "query"
Name = $_.InputObject.Name
Content = $_.InputObject.Content
}
Invoke-RestMethod -Method Put -Uri $uri -Header $header -Body $body
})
}
UPDATE: Here is the documentation that I was looking at, as requested.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-5.1
The API requires that the body be a JSON string. You can do a simple conversion (using ConvertTo-Json) in your Invoke-RestMethod command and set the content type accordingly.
Invoke-RestMethod -Method Put -Uri $uri -Header $header -Body ($body | ConvertTo-Json) -ContentType 'application/json'

Making a call to a Flask Restful API with invoke-restmethod and JWT auth

I have this API that I made with Flask (Python) and I am unable to get powershell to successfully make an API request to it. The problem is not the API because I tested it with postman and everything works as it should. More precisely it's when I add JWT token auth that it's not working with powershell, in my api the Create, Update and delete functions are protected with JWT token auth and the basic Read function have no auth at all. Below is the powershell code i am using:
Here is the function that generate my token (that part is working, note that I removed username and password from the function for security purposes):
function get-token {
param (
[Parameter(Position=0, Mandatory=$false)]
[string]$user,
[Parameter(Position=1, Mandatory=$false)]
[string]$password
)
$body = #{
username="$user"
password="$password"
}
$jsonbody = $body | ConvertTo-Json
$uri = "https://codegenius.live/api/auth"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept","application/json")
$headers.Add("Content-Type","application/json")
$response = Invoke-RestMethod -Uri $uri -Method Post -Body $jsonbody -Headers $headers
$response.access_token
}
This function will generate a token like this:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1ODIyMzA2OTUsImlhdCI6MTU4MjIzMDM5NSwibmJmIjoxNTgyMjMwMzk1LCJpZGVudGl0eSI6MX0.8wZZJEGxV7P4ZzN23eZ3d5-MGJ00N5zKHuCZXn9XRuw
Here is the call i am trying to make that doesn't work:
$body = #{
tpl_name="my template name"
tpl_subject="my template subject"
tpl_plaintext_content="bla bla bla"
tpl_html_content="bla bla bla"
}
$authheader = "JWT " + (get-token)
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept","application/json")
$headers.Add("Content-Type","application/json")
$headers.Add("Authorization",$authheader)
$jsonbody = $body | ConvertTo-Json
$uri = "https://codegenius.live/api/add-email"
$response = Invoke-RestMethod -Uri $uri -Method Post -Body $jsonbody -Headers $headers
The request response message is this one:
Invoke-RestMethod :
500 Internal Server Error
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server
is overloaded or
there is an error in the application.
Au caractère Ligne:25 : 17
+ ... $response = Invoke-RestMethod -Uri $uri -Method Post -Body $jsonbody ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation : (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-
RestMethod], WebEx
ception
+ FullyQualifiedErrorId :
WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
This is very strange because as I said it is working with Postman (see below images), I have tried googling the issue but I found no clue on how to actually solve this.
EDIT: the images show that in postman i used http instead of https, this is not the issue. In powershell http or https nothing works!
Change your line to this,
$authheader = "JWT $(get-token)"