Invoke webrequest удаленный сервер возвратил ошибку 401 несанкционированный

I’m attempting to POST a SOAP message to an Apache web server (Cisco Call Manager) using either the WebClient component of Powershell or the Invoke-WebRequest command. When using either function, I continue to get a «401 Unauthorized» response.
The server requires Basic Base64 encoded authentication. 

I can successfully post my content using SoapUI or cURL, however I would love to build this in Powershell. I’ve monitored the HTTP headers during the post in both Fiddler and SoapUI logs. 

When browsing to the URL i need to send the post too, I am prompted for authentication, after providing the authentication, I connect to the page and can POST my data. Based on that behavior and how the responses are being returned in Fiddler, it looks like
my Powershell command using either WebClient or Invoke-Webrequest, is send the request, however the server is responding with a 401 unauthorized and not trying to pass the credentials when it receives that response.

What I haven’t been able to figure out, is how to keep that session alive so that when the server sends back 401 and prompts for credentials, I can actually pass the credentials back and complete my POST.

Can anyone help out here and provide some sample code on how to accomplish this? Thanks.

I am getting below error while running below command for SharePoint url from powershell.

Invoke-WebRequest -UseDefaultCredentials -Uri http://spurl

Invoke-WebRequest : The remote server returned an error: (401)
Unauthorized.

asked Mar 15, 2016 at 10:43

ARD's user avatar

1

It’s a late answer, but i hope this can help someone else with the same problem:

        $username = "your domain/username"
        $password = ConvertTo-SecureString "your password" -AsPlainText -Force
        $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
        Invoke-WebRequest -Credential $cred -Uri http://spurl

answered Jan 18, 2017 at 14:19

Lykanox's user avatar

I’m working on a script to login to a sharepoint 2013 site and navigate to a few pages to make sure the site is working after updates and DR drills. I’m calling Invoke-WebRequest like this:

$site = Invoke-WebRequest -uri 'https://spsite' -Credential $(Get-Credential) -SessionVariable s

when I make the call I get a 401 Unauthorized error back. I have tried using basic authentication and building out the headers like this:

$u = 'domainuser'
$p = 'password'
$header = @{ Authorization = "Basic {0}" -f [convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $u,$p))) }

$site = Invoke-WebRequest -uri 'https://spsite' -Headers $header

with the same result. I’m hoping someone could offer another way to make this connection?

asked Feb 24, 2017 at 16:54

Mike Murray's user avatar

Mike MurrayMike Murray

1381 gold badge1 silver badge9 bronze badges

2

so I found a way to make this work in my situation and wanted to post the basics in case someone else runs into this.

I found that when the exception is thrown you can get the actual response from the web server from the exception object like this:

try{
    $site = Invoke-WebRequest -uri 'https://spsite' -Credential $(Get-Credential) -SessionVariable s
}
catch{
    $site = $_.Exception.Response
}

after that I was able to manipulate the $site variable to follow the redirection and submit the credentials as needed.

answered Feb 27, 2017 at 22:52

Mike Murray's user avatar

Mike MurrayMike Murray

1381 gold badge1 silver badge9 bronze badges

Use Export-PSCredential and Import-PSCredential from WFTools — you’ll only have to enter your credentials once per box, and it will last as long as your password doesn’t change: https://github.com/RamblingCookieMonster/PowerShell

Install-Module -Name WFTools -RequiredVersion 0.1.44

Import-Module WFTools;

$getCredentialMessage = "Please provide your Windows credentials";
$importedCredential = Import-PSCredential;
if ($importedCredential) {
    Write-Host -ForegroundColor Yellow "Imported your cached credential."
    while (-not $(Test-Credential -Credential $credential)) {
        Write-Host -ForegroundColor Yellow "Your cached credentials are not valid. Please re-enter."
        $credential = Get-Credential -Message $getCredentialMessage;
    }
    $credential = $importedCredential;
}
else {
    $credential = Get-Credential -Message $getCredentialMessage;
    while (-not $(Test-Credential -Credential $credential)) {
        $credential = Get-Credential -Message $getCredentialMessage;
    }
    Export-PSCredential $credential;
}

# Here is where the magic happens
$site = Invoke-WebRequest -uri 'https://spsite' -Credential $credential

answered Feb 27, 2018 at 19:33

John Zabroski's user avatar

John ZabroskiJohn Zabroski

2,1932 gold badges27 silver badges54 bronze badges

Dear community, 

I’m having trouble connecting to my companies Jira server using a powershell script and the Invoke-WebRequest commandlet.

I’m using the following script. Note that I’m getting the same error with any valid URI to this Jira server. While the same user can access all these URI’s through a webbrowser just fine.

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

$baseUrl = "https://MyDomain.atlassian.net"
$jql = "%22Epic Link%22 = SD-2"

$user = 'USER@MyDomain.com'
$pass = 'TheCorrectPassword'

$pair = "$($user):$($pass)"

$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))

$basicAuthValue = "Basic $encodedCreds"

$authHeader = @{
Authorization = $basicAuthValue
}

Invoke-WebRequest -uri $($baseUrl + "/rest/api/latest/search?jql=$jql") -Headers $authHeader -UseBasicParsing -ErrorAction Stop -Verbose

Output from powershell:

Invoke-WebRequest : The remote server returned an error: (401) Unauthorized.
At D:WorkJiraAccess2.ps1:22 char:1
+ Invoke-WebRequest -uri $($baseUrl + "/rest/api/latest/search?jql=$jql ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
eption
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Could there be a setting on the Jira Server that prevents this user from connecting via «Invoke-WebRequest»? Or is something wrong with my script?

Edit: I’m using the cloud version.

Если при get-запросе через Powershell и Invoke-Webrequest появляется ошибка «The remote server returned an error: (401) Unauthorized.», то необходимо использовать -UseDefaultCredentials.
В моем случае и это не помогло, сервер отвечал на запрос: данный браузер или операционная система не поддерживается. Помогло притвориться InternetExplorer через подмену UserAgent:

Invoke-WebRequest -Uri «http://site»-UseDefaultCredentials —UserAgent([Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer)

I made a Stack Overflow post about this here.

I’m trying to integrate Sage 50 Accounts Professional V23 with my external application through SData. So far I’ve tried connecting, with the SData address I got through Tools > Internet Options > SData Settings, but when I make the GET request using the credentials I used to sign in to Sage 50, I get 401 unauthorized error.

Sage 50 is hosted on Windows Server 2012, I’ve tried using PowerShell to make the request and tried using the browser; both fail.

This is the PowerShell code I used:

$username = "MyUsername"
$password = ConvertTo-SecureString 'MyPassword' -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
Invoke-WebRequest -Credential $cred -Uri 'http://localhost:5493/sdata/accounts50/GCRM/{string-of-numbers-letters-and-dashes}/salesOrders'

When going to the same url through the browser, a browser window pops up asking for authentication. I provide it, then click login, after doing that the windows pops up again with empty username and password. No matter how many times I fill them out, I get the same thing. If I click «Cancel» instead of login, then I get a 401 unauthorized error

Такое поведение возникает из-за перенаправления; при выполнении этого дополнительного запроса к месту перенаправления заголовок авторизации не включается.

По этой причине PowerShell 6.0.0 добавил параметр PreserveAuthorizationOnRedirect.

Indicates the cmdlet should preserve the Authorization header, when present, across redirections.
By default, the cmdlet strips the Authorization header before redirecting. Specifying this parameter disables this logic for cases where the header needs to be sent to the redirection location.

Справка по Invoke-WebRequest


В качестве альтернатива, если вы не используете PowerShell 6, вы можете обойти его с помощью сценария более низкого уровня с использованием System.Net.WebRequest, который определяет свойство AllowAutoRedirect, которое может быть установлено на False, чтобы пропустить перенаправление после успешного POST, избегая ошибки 401 .

Обратите внимание, что вы должны сами позаботиться о таких вещах, как форматирование данных / тела (json, form-urlencoded, …) и http-заголовки.

Скрипт будет выглядеть так, как показано ниже.
Обратите внимание на строку с AllowAutoRedirect = $false.

$creds = "$($BASIC_AUTH_USER):$($BASIC_AUTH_PASS)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($creds))
$basicAuthValue = "Basic $encodedCreds"

$url = "http://your.url"
$request = [System.Net.WebRequest]::CreateHttp($url);   
$request.Method = "post"
$request.Headers.Add("Authorization", $basicAuthValue)
$request.AllowAutoRedirect = $false

$body = "your formatted data goes here"
$bytes = [System.Text.Encoding]::UTF8.GetBytes($body);
$stream = $request.GetRequestStream()
$stream.Write($bytes, 0, $bytes.Length);
$stream.Close();

$request.GetResponse();

Понравилась статья? Поделить с друзьями:
  • Iphone выдает ошибку при активации
  • Iphone выдает ошибку не удается подключиться itunes
  • Iphone выдает ошибку аксессуар не поддерживается
  • Iphone восстановление прошивки ошибка 3194 при восстановлении iphone
  • Iphone 7 ошибка активации нет сети