JIRA Cloud API GET Request - Works in Postman, but not Powershell - powershell

I am able to perform a GET Request from Jira successfully in Postman, but am unable to make the same request in Powershell due to an authentication error. I know that my credentials are correct because there are or GET Requests that are successful. My guess is that it has something to do with the URL (https://arnold.jira.com/admin/rest/um/1/user).
Since I know that my credentials are correct, I am not sure what else I can try.
# Create a new session using the Jira REST API
$user = 'john.rambo#arnold.com'
$pass = '8675309'
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = #{
Authorization = $basicAuthValue;
Accept = 'application/json'
}
# Perform the GET Request
$UserEmail = 'dolf.lundgren#arnold.com'
$UserAttributeLink = 'https://arnold.jira.com/admin/rest/um/1/user?email=' + $UserEmail + '&expand=attributes'
$UserAttributes = Invoke-RestMethod ($UserAttributeLink) -Headers $Headers -Method GET -ContentType "application/json"
I expect to have the info returned, but am met with this error:
Invoke-RestMethod : User failed to authenticate
At line:12 char:19
+ ... ttributes = Invoke-RestMethod ($UserAttributeLink) -Headers $Headers ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (Method: GET, Reques\u2026PowerShell/6.2.1
}:HttpRequestMessage) [Invoke-RestMethod], HttpResponseException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Related

Invoke-RestMethod : The remote server returned an error: (403) Forbidden PowerShell

I want to get the display name and createdDateTime of Azure AD Groups by calling MS Graph from PowerShell.
For that, I'm using below PS Script:
$Body = #{
client_id = "app_id"
client_secret = "secret"
scope = "https://graph.microsoft.com/.default"
grant_type = 'client_credentials'
}
$Connect_Graph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/my_tenant_id/oauth2/v2.0/token" -Method Post -Body $Body
$token = $Connect_Graph.access_token
$query = "https://graph.microsoft.com/v1.0/groups/"
$groups = (Invoke-RestMethod -Headers #{Authorization = "Bearer $($token)"} -Uri $query -Method Get).value | Select displayName, createdDateTime
It failed with 403 Forbidden
Invoke-RestMethod : The remote server returned an error: (403) Forbidden.
At C:\Users\script.ps1:13 char:12
+ $groups = (Invoke-RestMethod -Headers #{Authorization = "Bearer $($to ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I have given permissions for Group.Read.All and Directory.Read.All.
Please check what type of permissions you granted for Group.Read.All and Directory.Read.All.
If you are trying to access the API as signed-in user, then you have to use Delegated permissions.
If you are trying to access the API without signed-in user, then you have to use Application permissions.
I executed the same script in my environment and got the same error when I have Delegated permissions without signed-in user like below:
To resolve the error, I granted Application permissions for Group.Read.All and Directory.Read.All and executed the below script:
$Body = #{
client_id = "app_id"
client_secret = "secret"
scope = "https://graph.microsoft.com/.default"
grant_type = 'client_credentials'
}
$Connect_Graph = Invoke-RestMethod -Uri "https://login.microsoftonline.com/my_tenant_id/oauth2/v2.0/token" -Method Post -Body $Body
$token = $Connect_Graph.access_token
$query = "https://graph.microsoft.com/v1.0/groups/"
(Invoke-RestMethod -Headers #{Authorization = "Bearer $($token)"} -Uri $query -Method Get).value | Select displayName, createdDateTime
And I got the results successfully like below:

Looping an invoke-RestMethod?

So I'm trying to automate a process at work which involves hitting SendGrid's API. For a short explanation.. with SendGrid you have Subusers and underneath those Teammates. There is no ready option to search all teammates, so you have to supply a subuser then display all teammates underneath. Rinse, repeat down the line. Well I'd like to automated as best as I can.
So the idea is to collect a teammate email address from then user then dump into a variable all the subusers then loop through those subusers looking for the $email variable.
I've never actually used loops in my scripts over the years so it's new territory for me and combining it with an invoke-restmethod just boggles me. heres what Ive got so far:
$token = 'xxxxxxxxxxxxxxxxxxx'
#First uri is to pull a list of subusers
$uri = "https://api.sendgrid.com/v3/subusers"
#Prompts for target email address
$email = Read-Host "Enter the users email"
$headers1 = #{"Authorization" = "Bearer $token"}
$headers2 = #{"Authorization" = "Bearer $token"
"on-behalf-of" = "$subuser"
}
$subs = Invoke-RestMethod -Method get -uri $uri -headers $headers1
$subarray = $subs | select-object username
foreach ($su in $subarray){
$teamarray = invoke-restmethod -method get -uri "https://api.sendgrid.com/v3/teammates?limit=500&offset=0" -headers $headers2
#$teamarray.gettype()
}
The last line is commented out.. i was trying to find teh type of the $teamarray data but it's giving this error for each loop through the subusers:
invoke-restmethod : {"errors":[{"field":null,"message":"authorization required"}]}
At line:18 char:18
+ ... teamarray = invoke-restmethod -method get -uri "https://api.sendgrid. ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod],
WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodComma
nd
This should mean the invoke-restmethod is malformed somehow. Any pointers would be appreciated!

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"

Connect Azure Data Catalog REST API using powershell

i want to connect to Azure Data Catalog RestAPI using power shell script and below is my script which failed to run.
Get an Access Token with ADAL
$authContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext ("{0}" -f $login)
$authenticationResult = $authContext.AcquireToken($ResourceId, $ClientId, $redirectUri, $PromptBehavior);
($token = $authenticationResult.AccessToken) | Out-File $accessToken
$authContext.AcquireToken($ResourceId, $ClientId, $redirectUri, $PromptBehavior)
$headers = #{
"Authorization" = ("Bearer {0}" -f $token);
}
$url = "https://api.azuredatacatalog.com/catalogs/DefaultCatalog/search/search?searchTerms=name:=Orders&count=10&api-version=2016-03-30"
$response = Invoke-RestMethod -Method GET -Uri $url -Headers $headers
I am getting below error message
Invoke-RestMethod :
401 - Unauthorized: Access is denied due to invalid credentials.
Server Error
401 - Unauthorized: Access is denied due to invalid credentials.
You do not have permission to view this directory or page using the credentials that you supplied.
At line:1 char:13
+ $response = Invoke-RestMethod -Method GET -Uri $url -Headers $headers
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
Please help me in resolving the issue
You might need to grant your application access to the Azure Data Catalog via Azure AD.
Do note that this may require Administrator Approval to complete.

Missing API key when making API RestMethod Call After HTTP Basic authentication in Mailchimp

In PowerShell, I was able to log in using HTTP Basic authentication For Mail Chimp.
$acctname = 'thisismyusername'
$password = 'thisismyapikey'
$params = #{
Uri = 'https://us14.api.mailchimp.com/3.0/';
Method = 'Get'; #(or POST, or whatever)
Headers = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($acctname):$($password)"));} #end headers hash table
} #end $params hash table
$var = Invoke-RestMethod #params
$var
When I try to get basic info on list thats id is "d3a7a4432d".
$URL = "https://us14.api.mailchimp.com/3.0/"
$Endpoint = "/lists/d3a7a4432d"
$URLMailChimp = "$URL$Endpoint"
$gist = Invoke-RestMethod -Method Get -Uri $URLMailChimp
I get this error message:
Invoke-RestMethod : {
"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
"title":"API Key Missing",
"status":401,
"detail":"Your request did not include an API key.",
"instance":""
}
At line:7 char:9
+ $gist = Invoke-RestMethod -Method Get -Uri $URLMailChimp
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I don't understand how to pass it my API key again. I thought by logging it it solved the issue.
I don't use MailChimp, but unless the first invocation provides you with an access token (and the documentation as well as your error message don't look like it would) you need to provide the authentication header with every request.
$acctname = 'thisismyusername'
$password = 'thisismyapikey'
$URL = 'https://us14.api.mailchimp.com/3.0/'
$listID = 'd3a7a4432d'
$auth = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${acctname}:${password}"))}
$gist = Invoke-RestMethod -Method Get -Uri "$URL/lists/$listID" -Headers $auth