403 Error using PowerShell 5 as Kentico 8.2 REST client - rest

This REST request works when I load it directly in a browser in which I'm simultaneously logged into the Kentico 8.2 admin site:
https://www.example.com/rest/CMS.SettingsKey
Now, I need to return the same results using PowerShell 5. I tried various versions of the following:
$url = "https://www.example.com/rest/CMS.SettingsKey"
$httpMethod = "Get"
$credentialsBytes = [System.Text.Encoding]::UTF8.GetBytes("username:password")
$credentialsEncoded = [System.Convert]::ToBase64String($credentialsBytes)
$headers = #{}
$headers.Add("Authorization", "Basic $($credentialsEncoded)")
$settings = (Invoke-RestMethod -Uri $url -Method $httpMethod -headers $headers)
Write-Host $settings
Note that "username" and "password" are the same credentials used to log into the admin site (when the REST request is working in the browser), and the user is a global admin.
The PS snippet gives me a 403 Forbidden error. I followed this page and this page, but I can't get it to work. What am I doing wrong?
EDIT:
I enabled the REST service, but now I'm getting a 401 Unauthorized error. Again, the user is a global admin. I get the feeling the headers aren't being included in the request (or that there is a problem with the headers), because the same request works (from PowerShell) if I generate a hash and use hash parameter authentication instead of basic authentication. I tried using Fiddler a bit as suggested in comments, but I'm new to it, and I don't have time to dive in too deep right now.

Just tested it using the latest hotfix versions (9.0.32 & 8.2.48) and it works just fine.
Make sure REST is enabled for the specific site (not only the global setting)
Make sure you have <modules runAllManagedModulesForAllRequests="true"> in your web.config as described here.

Related

How do I log on to JIRA in PowerShell using REST when basic authentication in plain text is blocked?

I've been trying to access our on-prem JIRA Server (configured with plain HTTP) using PowerShell Invoke-RestMethod, but I think I'm missing something.
The authentication header is created in base64
$cred = [convert]:.ToBase64String([text.encoding]::ASCII.GetBytes("account:password"))
$headers = #{Authorization = "Basic $cred"}
Using REST, I then ask for the issue (without posting any property filter to keep the request simple while I'm learning).
Invoke-RestMethod -Uri http://jiraserver:8080/jira-software/REST/agile/1.0/issue/test-1 `
-Headers $headers -ContentType "application/json" -AllowUnencryptedAuthentication
This obviously fails, as I get back a reply containing a login form
<form action="/login.jsp"
class="aui"
id="login-form"
method="post">
I do think I remember that basic authentication is no longer supported in JIRA.
How do I use OAuth in that case instead?
When working with another task that is well within the scope of AtlassianĀ“s PowerShell module JiraPS, I noticed a command called Invoke-JiraMethod.
It turns out that the module provides JIRA REST API access :)
So by setting up a JIRA session with the PowerShell module, I'll be able to use REST over an unencrypted connection.

getting 203 with error when using vsts rest api

When I'm trying to create a new work item in VSTS with the POST request:
https://galilinetsky.visualstudio.com/Automatiom/_apis/wit/workitems/$Test%20Case?api-version=5.0-preview.2
I get the next response :
Microsoft Internet Explorer's Enhanced Security Configuration is
currently enabled on your environment. This enhanced level of security
prevents our web integration experiences from displaying or performing
correctly. To continue with your operation please disable this
configuration or contact your administrator.
What am I doing wrong?
The solution is to be found in a similar question: Why I get Internet Explorer enhanced security error message in Chrome if I call VSO API from Angularjs SPA?
Andy writes
the PAT has to be prefix[ed] by ":" before you base 64 encode it"
So the solution is:
Create a Personal Access Token
Add a colon (':') before it
Encode the new PAT (with the preceding colon) using Base 64
Et voila ! That PAT will no longer give you a 203 error.
It's mainly caused by the PAT format is incorrect.
Such as if I add colon : before the PAT, the REST API will return with 203.
adding on to #numeratus
This question took awhile for me to get correctly on powershell. https://www.opentechguides.com/how-to/article/azure/201/devops-rest-powershell.html helped me greatly and a resulting simplified powershell request to azure apis
#enter your token in pat token
$pat = "xxx"
# Create header with PAT
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$header = #{authorization = "Basic $token"}
#enter your url in projects url
$projectsUrl = "https://feeds.dev.azure.com/"
$projects = Invoke-RestMethod -Uri $projectsUrl -Method Get -ContentType "application/json" -Headers $header

VSTS - Where has 'Allow Scripts to Access OAuth Token' gone?

I have VSTS builds that use the Powershell script to access the VSTS API, similar to that detailed in Microsoft's Documentation.
The document states:
To enable your script to use the build process OAuth token, go to the Options tab of the build definition and select Allow Scripts to Access OAuth Token.
After you've done that, your script can use to SYSTEM_ACCESSTOKEN
environment variable to access the VSTS REST API. For example:
Example:
$url = "$($env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI)$env:SYSTEM_TEAMPROJECTID/_apis/build-release/definitions/$($env:SYSTEM_DEFINITIONID)?api-version=2.0"
Write-Host "URL: $url"
$definition = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Definition = $($definition | ConvertTo-Json -Depth 1000)"
As detailed in Microsofts Documentation, I'm sure you used to go to Build > Options and click 'Allow Scripts to Access OAuth Token', but it is no longer there (see pic below).
When I try a build I get the following (which doesn't happen for my old builds):
Invoke-RestMethod :
{"$id":"1","innerException":null,"message":"TF400813: The user '' is
not authorized to access this
In addition, when I clone a build (which worked nicely when I did it 3 months ago), the property is set to false (it's set to true on the original).
UPDATE: If I export from VSTS, change that property and import again, it works, but I really need a solution without this sort of manual intervention.
How should this be done now please?
It is available in the agent phase now

Powershell and NITRO API for Citrix NetScaler error on GET method

I am using a PowerShell module provided by Citrix to invoke the Nitro REST API. Calling the function I can successfully add and remove load balanced services from the load. However when I try to do a GET method to get the status of a service I get the error:
Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
I have tried running Invoke-RestMethod without using the module but get the same error
Invoke-RestMethod -WebSession $myNSSession.WebSession -Method GET -Uri https://<NetScaler IP/nitro/v1/config/service/<Service Name>
When googling this error everything seems to point to certificate issues. I had this initially even on POST method until i added the below to my script
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
So since this works for doing POST i cant see why it wouldn't for a GET!!
another weird thing is, if I put the URL directly into the browser then enter my credentials i get a response in raw text! so it looks like this is an issue with the way i am calling it in PowerShell rather than the NetScaler or the NITRO API!
Someone please help as this is driving me crazy!!
Admitedly i am new to Invoke-RestMethod commands, but try this:
$creds = Get-Credential
$service = Invoke-RestMethod -Uri https://<NetScaler IP/nitro/v1/config/service/<Service Name> -Credential $creds
What you will get is something similar to this:
*errorcode* *message* *serverity* *service*
* 0 Done NONE {#{name=<service name; n..
then type $service.service and you will see more information. whatever attributes are availible will be listed. then just follow the pattern:
$service.service.
I had the same problem with Nitro API (specifically v10.5), and found that setting certificate policies, TLS versions and trust settings had no effect. POST works, GET fails.
The solution for me was to not use the cmdlets and instead drop back to a native .Net method. Below I am still using HTTPS with an internal certificate, hence still setting the callback.
$NSProtocol = "https://"
$NSHostname = "netscaler"
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$WebRequest = [System.Net.WebRequest]::Create("$NsProtocol$NsHostname/nitro/v1/config/hanode")
$WebRequest.Method = "GET"
$WebRequest.ContentType = "application/json; charset=utf-8";
$WebRequest.Headers.Add("AUTHORIZATION","Basic $([System.Convert]::ToBase64String([System.Text.Encoding]::GetEncoding("ISO-8859-1").GetBytes($nsuser+":"+$nspass)))")
$Response = $WebRequest.GetResponse()
$ReadStream = New-Object System.IO.StreamReader $Response.GetResponseStream()
$HaState = ConvertFrom-Json $ReadStream.ReadToEnd()
Hope that helps.

Send login username with REST API + Powershell

I've got the following Powershell script:
$url = "http://somerandomapikeyhere#prestashop.dev/my-store/api"
$request = [System.Net.WebRequest]::Create($url)
$response = $request.GetResponse()
echo $response
which attempts to access my Prestashop API REST service.
I can access the URL from Chrome without a problem, but in PowerShell I get a 401 Unauthorized response, which is understandeable as the somerandomapikeyhere bit in the URL needs to get dealt with differently in PowerShell.
The question is, how? Any ideas / advice?
It's not powershel, but the .net class that is not able to take an url in that format. You need to provide the credentials seperate. See here or here.
But if you have powershell v3 you are better off using the build in commands for web requests or even REST requests.
Invoke-restmethod -uri 'prestashop.dev/my-store/api' -credential 'someapikey'