Send login username with REST API + Powershell - rest

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'

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.

CURL script on Powershell to get a Response from HTTPS URL and also want to feed Username/Password

I am new to CURL and facing problems while writing a script to get a response from HTTPS URL.
Its failing at singleSignOn.
Basic command I am using is:
curl -UseBasicParsing https://abc.xyz.com.au -UseDefaultCredentials
Can someone please help with pointers how to force SSO on CURL while doing a check on HTTPS URL?
In Powershell Curl is really an alias for Invoke-WebRequest.
If you're new to this commandlet, start easy. Try using it with Google:
Invoke-WebRequest -Uri 'https://www.google.com'
Authentication is a little tricker. If the site uses basic authentication, you can use something like the following:
$credential= Get-Credential
Invoke-WebRequest -Uri 'https://foo.com' -Credential $credential
Depending on the application, you might have to construct the basic authentication headers yourself. There is a nice explanation of that in the post Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API
If the single-sign-on piece is using redirection, that's a different animal. You can use the Headers property on the response object to find the URL you're being redirected to. Jim McNatt has a nice article talking about that.

Deleting Gmail Emails via Google API using Powershell v2.0

$user = "example#gmail.com"
$pass= "examplepassword"
$secpasswd = ConvertTo-SecureString $user -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($pass, $secpasswd)
Invoke-RestMethod 'https://www.googleapis.com/gmail/v1/users/me/messages/0' -Method Delete -Credentials $cred
So, my problem here is twofold.
I originally tried using Invoke-WebRequest to delete gmail emails via the Google API with a http delete request. However, this did not work because Powershell 2.0 does not support Invoke-WebRequest.
Thereafter, I turned to attempting to utilize Invoke-RestMethod after experimentation with IMAP and POP3, which both required external dependencies (Adding .dlls to the machines I am working with is not optimal).
Therefore, if someone could show me the appropriate way to delete an email via the Google API in Powershell, I would appreciate it. I have provided some sample code as to what I am working with above. Please excuse any mistakes it may contain, as I am relatively new to Powershell, and my experience remains limited in working with RESTful services.
The GMail API is going to require Oauth2 authentication unless this is a gsuit / domain admin / GMail account in which case you can use a service account for authentication. In either case you cant use login and password.
My powershell knowledge is very limited have you considered doing this directly though the mail server IMAP and SMTP and not using the API. No idea if that's possible or not with powershell
Update:
I was able to do it using Invoke-WebRequest you will still need to get an access token first.
Invoke-WebRequest -Uri "https://www.googleapis.com/gmail/v1/users/me/messages/0?access_token=$accesstoken"-Method Get | ConvertFrom-Json
seams to also work
Invoke-RestMethod -Uri "https://www.googleapis.com/gmail/v1/users/me/messages/0?access_token=$accesstoken"-Method Get
Put up a the code for OAuth on GitHub if your interested: Google Oauth Powershell

403 Error using PowerShell 5 as Kentico 8.2 REST client

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.

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.