2

I'm attempting to write a PowerShell script that will automate the process of adding new user accounts to our Jira instance. I've provided my code but I'm honestly not even getting to that point as I am receiving a 401 error:

This resource requires WebSudo.

I have seen these two posts on the Jira support forum but it's not clear to me how I could adapt the code to get and then apply it to my REST call. I would be fine with changing this to use the .Net WebClient class if that would make all of this easier, but right now I'm at a bit of a loss.

$url = "https://devjira.domain.com/rest/api/2/user"


$user = "admin"
$pass = "super secure password"
$secpasswd = ConvertTo-SecureString $user -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($pass, $secpasswd);

$userObject = @{
    name     = "rkaucher@domain.net";
    emailAddress = "robert_kaucher@domain.com";
    displayName  = "Bob Kaucher";
    notification = $true;
}

$restParameters = @{
    Uri = $url;
    ContentType = "application/json";
    Method = "POST";
    Body = (ConvertTo-Json $userObject).ToString();
    Credential = $cred;

}

Invoke-RestMethod @restParameters

JSON output

{
    "name":  "rkaucher@domain.net",
    "displayName":  "Bob Kaucher",
    "emailAddress":  "robert_kaucher@domain.com",
    "notification":  true
}
Robert Kaucher
  • 1,841
  • 3
  • 22
  • 44

1 Answers1

2

I changed the authentication component of my script to this:

$cred = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$user`:$pass"))
$headers = @{Authorization=("Basic $cred")} 

This was based on the selected answer to the following:

PowerShell's Invoke-RestMethod equivalent of curl -u (Basic Authentication)

The final invocation of the method looks like this:

$restParameters = @{
    Uri = $url;
    ContentType = "application/json";
    Method = "POST";
    Body = (ConvertTo-Json $userObject).ToString();
    Headers = $headers;
}

$response = Invoke-RestMethod @restParameters
Community
  • 1
  • 1
Robert Kaucher
  • 1,841
  • 3
  • 22
  • 44
  • 2
    This happens because `Invoke-RestMethod` and `Invoke-WebRequest` always submit the request without credentials first, and wait for a 401 response before re-sending the request with credentials, because this is how the RFC defines the behavior. It's increasingly common for web services to not reply with a 401 (choosing for example, a 404 instead), sometimes as a way of obscuring the fact that a particular resource is valid from anonymous requests. – briantist Aug 04 '15 at 21:57
  • @briantist - Thanks for the explanation. That makes perfect sense. – Robert Kaucher Aug 04 '15 at 21:59