I'm a PowerShell novice and I inherited some code that's forced me to use Powershell7 over 5.1 on my Windows Server 2012 and now I can't get my credentials to authenticate across the organisation's proxy. I'm thinking there's something in the Powershell7 environment that's not installed/no longer supported/not configured correctly. The code below works in 5.1 but in 7, I get a message back from our proxy saying it's missing credentials. Can anyone shed light on what to do?
#*************************************************************************
# Proxy Credentials
#*************************************************************************
[system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy('http://proxy.############')
$username ="###################"
$password ="###################"
$securePwd = $password| convertto-securestring -AsPlainText -Force
$Creds=new-object System.Management.Automation.PSCredential ($username,$securePwd)
$Wcl=New-Object System.Net.WebClient
$Wcl.Proxy.Credentials=$Creds
#*************************************************************************
# Authentication Call
#*************************************************************************
$uri = 'https://testapi.com/web/authenticate'
$params = '{"userName": "######",
"password": "########"
}'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$token =Invoke-Webrequest -Method Post -Uri $uri -body $params -ContentType "application/json" -UseBasicParsing |ConvertFrom-Json | Select AuthenticateResult
write-host $token
#*************************************************************************
This was something specific to the service account I was using to log in to the server. Changed the account and it worked on both versions. No idea what the difference was but I got what I needed.
Related
The following PowerShell invoke-webrequest works for me when the Windows Service I'm running it from has permission to call the webservice. However, this isn't always the case.
I need to the ability to use Windows Authentication but also set the account username\password for the call. Does anyone have some sample code for doing this?
Invoke-WebRequest -UseBasicParsing "url" -UseDefaultCredentials -Method GET
You may set the UseDefaultCredentials property of Invoke-WebRequest module to true. Link to the official doc: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-6
$url = "http://yourURL"
$wc = New-Object System.Net.WebClient
$wc.UseDefaultCredentials = $true
$response = $wc.DownloadString($url)
I would like to call a remote Rest web service from a Windows server hosting the remote certificate.
I've exported the certificate from the remote server and added it to the Windwos store. (/Personal/myCert)
I would like to use it on a Invoke-RestMethod PowerShell command.
Here bellow is the code I've tried
# Variables
$Remote_Uri = "https://remote.example.com/service/search"
$Remote_CertificateName = "myCert"
$Remote_ApiKey = "oisdjfSOEDJFKQDfSDKFjsQDKFJ"
$Remote_ContentType = "application/json"
$LocalArtifactPath = "C:\RemoteObjects.json"
# Get Certificate
$Remote_CertificateThumbprint = (Get-ChildItem -Path Cert:\LocalMachine\My | Where-Object {$_.Subject -match $Remote_CertificateName}).Thumbprint;
$Certificate = Get-ChildItem -Path Cert:\LocalMachine\My\$Remote_CertificateThumbprint
# Basic Encoding
$encoding = [System.Text.Encoding]::ASCII.GetBytes($Certificate)
$encodedString = [System.Convert]::ToBase64String($encoding)
$BasicAuth = "Basic " + $encodedString
# Set Headers
$Headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$Headers.Add("Authorization", $BasicAuth)
$Headers.Add("api", $Remote_ApiKey)
$Headers.Add("Content-Type", $Remote_ContentType)
# Self-signed certificate
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = { $true }
# Call Rest Service
Invoke-RestMethod -Method Get -Uri $Remote_Uri -OutFile $LocalArtifactPath -Headers $Headers
Invoke-RestMethod -Method Get -Uri $Remote_Uri -OutFile $LocalArtifactPath -Certificate $Certificate
Invoke-RestMethod -Method Get -Uri $Remote_Uri -OutFile $LocalArtifactPath -CertificateThumbprint $Remote_CertificateThumbprint
# Self-signed certificate off
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null
The three lines with Invoke-RestMethod commands failed with respectively :
Wrong header (this was expected but I gave it a try)
Authorization is empty or scheme is not basic
Certificate thumbprint not found
I've got the rest call working with #{"AUTHORIZATION"="Basic Base64Encode(user:pass)"} so I can tell the service is answering but I would like not to use user:pass in my script.
I would like to use the Certificate I've added to the Windows Store.
I'm wondering about two things :
Is the "Basic" authorization scheme is the good one to use with a certificate ?
In powershell, how to use a certificate from the local windows store running Invoke-RestMethod command ?
Thank you for your help
Adding this [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 in my script fixed the "The underlying connection was closed" issue.
Before this crosscheck whether IIS is enabled in your system.
While I use the method mentioned in this thread PowerShell's Invoke-RestMethod equivalent of curl -u (Basic Authentication) I could get connected to REST API without a 401 error.
However currently I am giving my password in Plain Text.
I want a way to use a Hash of my password and then use it in the script.
The script then should be able to decrypt it too. But I don't want others who have access to the script, be able to decrypt it.
So I don't want to expose the decryption algorithm as well to any.
Proposed method I am thinking of:
Combine existing HASH algorithms in a mixed random way (by feeding the HASH of one algorithm to another) which only I know and then have a custom Powershell function/cmdlet/whatever in the script which knows to decrypt.
Is there a simpler and better way?
Before I try the proposed method I would like to hear from others on any better ways.
Entire script is as below.
$User = "domain\userName"
$uri = "https://TeamProjectCollectionURI/TeamProjectName/_apis/build/builds"
$securePassword = ConvertTo-SecureString 'PasswordWhichContains$asWell' -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($User, $securePassword)
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$credential)))
$response = Invoke-RestMethod -Method Get -Uri $uri -Credential $credential -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -ContentType application/json
$response
You can pass a username and password (masked as a secret variable) through PowerShell into a PSCredential object and use the -Credential switch when invoking the REST method:
$securePassword = $Password | ConvertTo-SecureString -AsPlainText -Force $credential = New-Object System.Management.Automation.PSCredential($User, $securePassword)
$releaseresponse = Invoke-RestMethod -Method Get -Credential $credential -ContentType application/json -Uri $Uri
More detail info please refer this blog: VSTS/TFS REST API: The basics and working with builds and releases
You can convert your password to encrypted string and use the encrypted string in your PowerShell script.
Convert to encrypted string:
$securePassword = ConvertTo-SecureString "Yourpassword" -AsPlainText -Force
$encryptedPwd = ConvertFrom-SecureString -SecureString $securePassword
Write-Host $encryptedPwd
Record the generated encrypted string and use it in your script.
$securePassword = ConvertTo-SecureString -String "Encrypted String"
I need to create a PowerShell script to upload a file to Archiva repository
I managed to do this by this sample:
$user = "user"
$pass = "password"
$secpass = ConvertTo-SecureString $pass -AsPlainText -Force
$uri = "http:*//X.X.X.X:8080/repository/win/test/test/1.6/test.exe"
$filePath = "x:\x\test.exe"
$cred = New-Object System.Management.Automation.PSCredential ($user, $secpass)
Invoke-RestMethod -Credential $cred -Uri $uri -Method Put -InFile $filePath -ContentType "multipart/form-data"
but it can't create or correct a maven-metadata.xml and a need that for version control. I want it to work like the upload trough Archiva UI.
So maybe somebody can help my with a script for upload using Archiva rest API by PowerShell.
I need to use this services from API
/archivaUiServices/fileUploadService
/fileUploadService/save/{repositoryId}/{groupId}/{artifactId}/{version}/{packaging}
, but don't know the correct way of using them in Powershell
(Managed to reproduce an upload by copping the request caught in fiddler)
Won't work as it.
You need to PUT (http method) your jar to the maven path.
http://yourinstantce/{repositoryId}/{groupId}/{artifactId}/{version}
I'm trying to write a PowerShell script to have a one click solution to uploading and building my mobile application. I have successfully done this using cURL but was trying to use native PowerShell commands instead. In cURL I can use the -F (--form) parameter and pass the zip file (e.g. -F file=#C:...\www.zip). I cannot figure out how to achieve this same thing using PowerShell. I am trying to use Invoke-RestMethod but not sure if this is correct. Here's a link to the PhoneGap API:
https://build.phonegap.com/docs/write_api
Any help would much appreciated!
Invoke-RestMethod -Uri https://build.phonegap.com/api/v1/apps/:id -Headers #{Authorization='Basic username-and-password-in-base64'} -Method Put -InFile "www.zip"
username-and-password-in-base64 is your Adobe/PhoneGap Build username and password combined into a string "username:password" and encoded using Base64 (http://www.base64decode.org/).
:id in the url is your app id in phonegap build.
Try something like this:
$pathToZip = "bin/phonegap.zip"
$user = "user"
$pass = "password"
## convert to secure password since we can't use get-credential in non interactive mode
$securepass = ConvertTo-SecureString $pass -AsPlainText -Force
## create a PSCredential object
$credential = New-Object System.Management.Automation.PSCredential($user, $securepass)
$appId = "12345"
$url = "https://build.phonegap.com/api/v1/apps/" + $appId;
Write-Host $url
Invoke-RestMethod -Uri $url -Credential $credential -Method Put -InFile $pathToZip