I am trying to connect to a Neo4j via Invoke-RestMethod (PowerShell versions 3,4,5).
Based on web recommendations, I am setting URI:
$Uri = "http://localhost:7474/db/data/cypher"
... followed by a call to invoke rest method (POST or GET, does not matter)
Invoke-RestMethod -Uri $Uri -Method Post -Body $Body -ContentType 'application/json'
Message I get is:
System.Net.WebException: The remote server returned an error: (401) Unauthorized.
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.GetResponse(WebRequest request)
at Microsoft.PowerShell.Commands.WebRequestPSCmdlet.ProcessRecord()
I tried putting in http://userId/pwd#localhost:7474....
but the error is the same.
Is there another way to pass authentication information to Neo4j?
Disabling security is not an option.
Thank you!
--Alex
The authetication havs to bee the http standard authentication. You can do this in powershell for example with the following code.
$user = 'user'
$pass = 'pass'
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = #{
Authorization = $basicAuthValue
}
Invoke-RestMethod -Uri $Uri -Method Post -Body $Body -ContentType 'application/json' -Headers $Headers
Background
The error code 401 says that the authentication is not correct on the server.
I found this information in the documentation.
https://neo4j.com/docs/developer-manual/3.4/http-api/authentication/
Related
I need to add user permission when creating an environment through REST API with PowerShell.
I've looked at the network trace and this is the header when I tried to manually add a user permissions
Request URL:
https://dev.azure.com/{org}/_apis/securityroles/scopes/distributedtask.environmentreferencerole/roleassignments/resources/{project_id}_{env_id}
Request Method: Put
Request Body:
[{userId: "{id_of_user}", roleName: "Administrator"}]
And this is the code I tried:
# other code
...
$body = #(
#{ 'userId' = '{id_of_user}'; 'roleName': 'Administrator' }
) | ConvertTo-Json
Invoke-RestMethod -Uri $uri -Method Put -Body $body -ContentType "application/json" -Headers $header
But it is returning:
{"count":0,"value":{}}
The only missing thing is that in your body, you should provide an array instead of a single object, here is a working example:
$uri = "https://dev.azure.com/bauca/_apis/securityroles/scopes/distributedtask.environmentreferencerole/roleassignments/resources/{project_id}_{env_id}"
$id_of_user = 'YOUR_USER_ID'
$tokenbase = 'YOUR_PAT'
$header = #{
"authority"="dev.azure.com"
"Authorization"= "Basic $tokenbase"
"method"="PUT"
"path"="/{ORG}/_apis/securityroles/scopes/distributedtask.environmentreferencerole/roleassignments/resources/{project_id}_{env_id}"
"scheme"="https"
"accept"="application/json;api-version=5.0-preview.1;excludeUrls=true;enumsAsNumbers=true;msDateFormat=true;noArrayWrap=true"
"accept-encoding"="gzip, deflate, br"
"accept-language"="en-US,en;q=0.9,pt;q=0.8,nl;q=0.7"
"origin"="https://dev.azure.com"
"x-vss-reauthenticationaction"="Suppress"
} `
$body = "[{`"userId`":`"${id_of_user}`",`"roleName`":`"Administrator`"}]"
Invoke-RestMethod -UseBasicParsing -Uri $uri -Method "PUT" -Body $body -ContentType "application/json" -Headers $header
The returned results should be something like:
#{displayName=USER_NAME; id=USERID; uniqueName=USER_UNIQUENAME}
The API documentation is not clear about that, so, in this situations what I'd recommend you to do, is just use Chrome to do the requests through the UI, then inspect element and grab the network information of the request, after that 'Click with the right button' and then select 'Copy to Powershell' you'll see exactly what is the 'body' required to perform the request.
Trying to connect to a REST-API via Powershell client. When testing the endpoint in Postman, I have no problems at all. Here's the main part of the function (I have a [pscredential]$Creds parameter that I use to get the username and password):
[string]$username = $Creds.UserName
[string]$password = (New-Object System.Net.NetworkCredential($Creds.UserName, $Creds.Password, 'Null')).Password
[string]$authorizationInfo= ([Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(('{0}:{1}' -f $username, $password))))
Invoke-WebRequest -Uri "https://$($HostName)/api/" -Method Get -Headers #{Authorization = ('Basic {0}' -f $authorizationInfo)}
For some reason the Authorization header is different in my script than in Postman. I can even copy the Authorization header out of Postman and paste it into the -Headers parameter and everything works fine. I just don't see where I'm getting this wrong.
I can't tell you why that's not working, but I can suggest something that works for me all the time with APIs:
$auth = $username + ':' + $upassword
$Encoded = [System.Text.Encoding]::UTF8.GetBytes($auth)
$authorizationInfo = [System.Convert]::ToBase64String($Encoded)
$headers = #{"Authorization"="Basic $($authorizationInfo)"}
Invoke-WebRequest -Uri "https://$($HostName)/api/" -Method GET -Headers $headers
If that doesn't work, try this subtle difference with Invoke-Restmethod:
Invoke-RestMethod -Uri "https://$($HostName)/api/" -Method GET -Headers $headers
Working with APIs is always an adventure. Keep trying. :)
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)"
I added powershell script in azure devops release and try to send POST request using Invoke-WebRequest with Authorization token and xml file.
What am I doing wrong?
I get Authorization token from another POST request and tried to create headers with this token and trying send xml file using x-ray endpoint (NUnit XML results - POST /api/v1/import/execution/nunit)
https://confluence.xpand-it.com/display/XRAYCLOUD/Import+Execution+Results+-+REST#ImportExecutionResults-REST-NUnitXMLresults
Authorization token like headers parameters
Content-type like powershell parameters
$bodyForAuth=#{"client_id"="...";
"client_secret"="...";
}
$jsonAuth=Invoke-WebRequest -Uri $urlForAuth -Method POST -Body ($bodyForAuth|ConvertTo-Json) -ContentType "application/json"
$authToken=ConvertFrom-Json -InputObject $jsonAuth
$headers=#{ Authorization = "Bearer $authToken" }
Invoke-WebRequest -Headers $headers -Uri $urlForXrayApi -Method POST -ContentType "text/xml" -InFile $TestResultsXmlPath
And I have error: "Invoke-RestMethod : Could not find authentication data on request"
Also I try to send like this:
$headers=#{ Authorization = "Bearer $authToken";"Content-Type"="text/xml" }
Invoke-WebRequest -Headers $headers -Uri $urlForXrayApi -Method POST -InFile $TestResultsXmlPath
And also have the same error : "Invoke-RestMethod : Could not find authentication data on request"
But if I send POST request like this (without Content-Type):
$bodyForAuth=#{"client_id"="...";
"client_secret"="...";
}
$jsonAuth=Invoke-WebRequest -Uri $urlForAuth -Method POST -Body ($bodyForAuth|ConvertTo-Json) -ContentType "application/json"
$authToken=ConvertFrom-Json -InputObject $jsonAuth
$headers=#{ Authorization = "Bearer $authToken" }
Invoke-WebRequest -Headers $headers -Uri $urlForXrayApi -Method POST -InFile $TestResultsXmlPath
I have SERVER ERROR: "Invoke-RestMethod : {"error":"Missing data in the nunit results import request"}"
Power Shell v. 5.1
Why when I send to headers server can not fine authorization data?
I needed parenthesis, so I changed $TestResultsXmlPath to $(TestResultsXmlPath)
Invoke-WebRequest `
-Headers $headers `
-Uri $urlForXrayApi `
-Method POST `
-InFile $(TestResultsXmlPath)
I am trying to connect to Azure Machine Learning Web service using Invoke-WebRequest in PowerShell. after bellow command I will get an error that "Request is unauthorized to access
resource.":
Invoke-WebRequest -Uri $Url -Method POST -Body $body
As I know, you can connect to a Machine Learning Web service using any programming language that supports HTTP request and response. read more about it here.
Seems I need to pass API Key with my request. I have tried this two types of command, but the error was same:
Invoke-WebRequest -Uri $Url -Method POST -Body $body -Headers #{'apikey' = $API_key}
and
Invoke-WebRequest -Uri $Url -Method POST -Body $body -Header #{ "X-ApiKey" = $API_key }
Can you please guide me how I can pass API Key to the Azure Machine Learning Web service using PowerShell?
Per TheIncorrigible's comment, try this:
Invoke-WebRequest -Uri $Url -Method POST -Body $body -Headers #{ Authorization = "Bearer " + $API_key }
You are passing a JSON string, so you could also just use the ConvertTo-Json command to create your true API key. For info on that check this out: using powershell with JSON data
You should use this:
Invoke-WebRequest -Uri $Url -Method POST -Body $body -Headers #{ 'Content-Type' = 'application/json'; 'Authorization' = "Bearer " + $API_key }