AtlassianPS / JiraPS

PowerShell module to interact with Atlassian JIRA
https://AtlassianPS.org/module/JiraPS
MIT License
323 stars 131 forks source link

New-JiraSession saying "The user could not be authenticated" #350

Closed DavidHromyk closed 5 years ago

DavidHromyk commented 5 years ago

Description

All of my current coworkers except for myself are currently not able to authenticate with New-JiraSession even though their credentials are correct.

Steps To Reproduce

  1. My -verbose -debug:
    
    PS C:\Users\david.hromyk> New-JiraSession -Verbose -Debug
    cmdlet New-JiraSession at command pipeline position 1
    Supply values for the following parameters:
    VERBOSE: [New-JiraSession] Function started
    VERBOSE: [Get-JiraConfigServer] Function started
    DEBUG: [Get-JiraConfigServer] ParameterSetName: __AllParameterSets
    DEBUG: [Get-JiraConfigServer] PSBoundParameters: 
    Key         Value
    ---         -----
    ErrorAction  Stop

VERBOSE: [Get-JiraConfigServer] Complete DEBUG: [New-JiraSession] ParameterSetName: __AllParameterSets DEBUG: [New-JiraSession] PSBoundParameters: Key Value


Verbose True
Debug True
Credential System.Management.Automation.PSCredential

DEBUG: [New-JiraSession] Invoking JiraMethod with $parameter VERBOSE: [Invoke-JiraMethod] Function started DEBUG: [Invoke-JiraMethod] ParameterSetName: __AllParameterSets DEBUG: [Invoke-JiraMethod] PSBoundParameters: Key Value


Credential System.Management.Automation.PSCredential
Method Get
Headers {}
URI https://faithlife.atlassian.net/rest/api/2/mypermissions StoreSession True

VERBOSE: [ConvertTo-GetParameter] Making HTTP get parameter string out of a hashtable VERBOSE: Name Value


maxResults 25

VERBOSE: [Invoke-JiraMethod] Get https://faithlife.atlassian.net/rest/api/2/mypermissions?maxResults =25 DEBUG: [Invoke-JiraMethod] Invoke-WebRequest with $splatParameters: Name Value


ErrorAction Stop
SessionVariable newSessionVar
Headers {Accept-Charset, Accept}
ContentType application/json; charset=utf-8
Credential System.Management.Automation.PSCredential
Method Get
Uri https://faithlife.atlassian.net/rest/api/2/mypermissions?maxResul... UseBasicParsing True
Verbose False

DEBUG: [Invoke-JiraMethod] Executed WebRequest. Access $webResponse to see details VERBOSE: [Test-ServerResponse] Checking response headers for authentication errors DEBUG: [Test-ServerResponse] Investigating $InputObject.Headers['X-Seraph-LoginReason'] VERBOSE: [Invoke-JiraMethod] Status code: 200 DEBUG: [ConvertTo-JiraSession] Converting $InputObject to custom object VERBOSE: [Invoke-JiraMethod] Function ended DEBUG: [New-JiraSession] Adding session result to existing module PrivateData

VERBOSE: [New-JiraSession] Complete Username WebSession


david.hromyk Microsoft.PowerShell.Commands.WebRequestSession

My coworkers behavior: 
```Powershell
PS C:\Users\david.hromyk> New-JiraSession -Verbose -Debug
cmdlet New-JiraSession at command pipeline position 1
Supply values for the following parameters:
VERBOSE: [New-JiraSession] Function started
VERBOSE: [Get-JiraConfigServer] Function started
DEBUG: [Get-JiraConfigServer] ParameterSetName: __AllParameterSets
DEBUG: [Get-JiraConfigServer] PSBoundParameters: 
Key         Value
---         -----
ErrorAction  Stop

VERBOSE: [Get-JiraConfigServer] Complete
DEBUG: [New-JiraSession] ParameterSetName: __AllParameterSets
DEBUG: [New-JiraSession] PSBoundParameters: 
Key        Value                                    
---        -----                                    
Verbose    True                                     
Debug      True                                     
Credential System.Management.Automation.PSCredential

DEBUG: [New-JiraSession] Invoking JiraMethod with $parameter
VERBOSE: [Invoke-JiraMethod] Function started
DEBUG: [Invoke-JiraMethod] ParameterSetName: __AllParameterSets
DEBUG: [Invoke-JiraMethod] PSBoundParameters: 
Key          Value                                                   
---          -----                                                   
Credential   System.Management.Automation.PSCredential               
Method       Get                                                     
Headers      {}                                                      
URI          https://faithlife.atlassian.net/rest/api/2/mypermissions
StoreSession True                                                    

VERBOSE: [ConvertTo-GetParameter] Making HTTP get parameter string out of a hashtable
VERBOSE: 
Name                           Value                                                               
----                           -----                                                               
maxResults                     25                                                                  

VERBOSE: [Invoke-JiraMethod] Get https://faithlife.atlassian.net/rest/api/2/mypermissions?maxResults
=25
DEBUG: [Invoke-JiraMethod] Invoke-WebRequest with $splatParameters: 
Name                           Value                                                               
----                           -----                                                               
ErrorAction                    Stop                                                                
SessionVariable                newSessionVar                                                       
Headers                        {Accept-Charset, Accept}                                            
ContentType                    application/json; charset=utf-8                                     
Credential                     System.Management.Automation.PSCredential                           
Method                         Get                                                                 
Uri                            https://faithlife.atlassian.net/rest/api/2/mypermissions?maxResul...
UseBasicParsing                True                                                                
Verbose                        False                                                               

VERBOSE: [Invoke-JiraMethod] Failed to get an answer from the server
DEBUG: [Invoke-JiraMethod] Executed WebRequest. Access $webResponse to see details
VERBOSE: [Test-ServerResponse] Checking response headers for authentication errors
DEBUG: [Test-ServerResponse] Investigating $InputObject.Headers['X-Seraph-LoginReason']
Invoke-JiraMethod : The user could not be authenticated.
At C:\Users\david.hromyk\Documents\WindowsPowerShell\Modules\JiraPS\2.10.3\JiraPS.psm1:3676 char:19
+         $result = Invoke-JiraMethod @parameter
+                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : AuthenticationError: (:) [Invoke-JiraMethod], HttpRequestException
    + FullyQualifiedErrorId : AuthenticationFailed,Invoke-JiraMethod

DEBUG: [New-JiraSession] Adding session result to existing module PrivateData
VERBOSE: [New-JiraSession] Complete

Expected behavior

I expect that they are able to authenticate since they all have the same permissions. They were able to authenticate at one point.

lipkau commented 5 years ago

hello @DavidHromyk

I am unable to see how you are passing the credentials to New-JiraSession. Can you please do it like this

$cred = Get-Credential
New-JiraSession -Credential $cred

so that you can inspect the credentials like this

$cred.UserName + " : " + $cred.GetNetworkCredential().Password

You can make sure that the usename is correct by trying to open https://faithlife.atlassian.net/secure/ViewProfile.jspa?name=USERNAME

DavidHromyk commented 5 years ago

Fwiw @lipkau we are passing the Jira credentials with

$cred = Get-Credential
New-JiraSession -Credential $cred

also confirmed that the usernames are correct by visiting that URL. Below is another coworkers output. This is a bummer so far since we use a PS creation script for our account setups that uses this module. I am just baffled as to why it stopped working.

PS C:\Users\millie.mulka> $cred = Get-Credential
>> New-JiraSession -Credential $cred -Debug -Verbose

cmdlet Get-Credential at command pipeline position 1
Supply values for the following parameters:
Credential
VERBOSE: [New-JiraSession] Function started
VERBOSE: [Get-JiraConfigServer] Function started
DEBUG: [Get-JiraConfigServer] ParameterSetName: __AllParameterSets
DEBUG: [Get-JiraConfigServer] PSBoundParameters:
Key         Value
---         -----
ErrorAction  Stop

VERBOSE: [Get-JiraConfigServer] Complete
DEBUG: [New-JiraSession] ParameterSetName: __AllParameterSets
DEBUG: [New-JiraSession] PSBoundParameters:
Key        Value
---        -----
Credential System.Management.Automation.PSCredential
Debug      True
Verbose    True

DEBUG: [New-JiraSession] Invoking JiraMethod with $parameter

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): a
VERBOSE: [Invoke-JiraMethod] Function started
DEBUG: [Invoke-JiraMethod] ParameterSetName: __AllParameterSets
DEBUG: [Invoke-JiraMethod] PSBoundParameters:
Key          Value
---          -----
Credential   System.Management.Automation.PSCredential
Method       Get
Headers      {}
URI          https://faithlife.atlassian.net/rest/api/2/mypermissions
StoreSession True

VERBOSE: [ConvertTo-GetParameter] Making HTTP get parameter string out of a hashtable
VERBOSE:
Name                           Value

----                           -----

maxResults                     25

VERBOSE: [Invoke-JiraMethod] Get https://faithlife.atlassian.net/rest/api/2/mypermissions?maxResults=25
DEBUG: [Invoke-JiraMethod] Invoke-WebRequest with $splatParameters:
Name                           Value

----                           -----

ErrorAction                    Stop

SessionVariable                newSessionVar

Headers                        {Accept-Charset, Accept}

ContentType                    application/json; charset=utf-8

Credential                     System.Management.Automation.PSCredential

Method                         Get

Uri                            https://faithlife.atlassian.net/rest/api/2/mypermissions?maxResults=25

UseBasicParsing                True

Verbose                        False

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): a
VERBOSE: [Invoke-JiraMethod] Failed to get an answer from the server
DEBUG: [Invoke-JiraMethod] Executed WebRequest. Access $webResponse to see details

Confirm
Continue with this operation?
[Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): a
VERBOSE: [Test-ServerResponse] Checking response headers for authentication errors
DEBUG: [Test-ServerResponse] Investigating $InputObject.Headers['X-Seraph-LoginReason']
Invoke-JiraMethod : The user could not be authenticated.
At C:\Users\millie.mulka\Documents\WindowsPowerShell\Modules\JiraPS\2.10.3\JiraPS.psm1:3676 char:19
+         $result = Invoke-JiraMethod @parameter
+                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : AuthenticationError: (:) [Invoke-JiraMethod], HttpRequestException
    + FullyQualifiedErrorId : AuthenticationFailed,Invoke-JiraMethod

DEBUG: [New-JiraSession] Adding session result to existing module PrivateData
VERBOSE: [New-JiraSession] Complete

Also confirmed the passwords are correct with


$cred.UserName + " : " + $cred.GetNetworkCredential().Password
lipkau commented 5 years ago

Please enter suspend mode at the last debug message DEBUG: [Invoke-JiraMethod] Executed WebRequest. Access $webResponse to see details and show me the content of

$webresponse;$webresponse.headers
DavidHromyk commented 5 years ago

Here is my $webresponse;$webresponse.headers

PS C:\Users\david.hromyk>> $webResponse;$webResponse.headers
True

StatusCode        : 200
StatusDescription : 
Content           : {"permissions":{"VIEW_WORKFLOW_READONLY":{"id":"45","key":"VIEW_WORK
                    FLOW_READONLY","name":"View Read-Only Workflow","type":"PROJECT","de
                    scription":"admin.permissions.descriptions.VIEW_WORKFLOW_READONL...
RawContent        : HTTP/1.1 200 
                    Vary: Accept-Encoding
                    Strict-Transport-Security: max-age=315360000; includeSubDomains; 
                    preload
                    ATL-TraceId: 3e5b272337f1268e
                    X-AACCOUNTID: 557058%3A74595148-5c8d-43c6-a9c3-adef4db3aa...
Forms             : 
Headers           : {[Vary, Accept-Encoding], [Strict-Transport-Security, 
                    max-age=315360000; includeSubDomains; preload], [ATL-TraceId, 
                    3e5b272337f1268e], [X-AACCOUNTID, 
                    557058%3A74595148-5c8d-43c6-a9c3-adef4db3aa74]...}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : 
RawContentLength  : 14706

Key   : Vary
Value : Accept-Encoding

Key   : Strict-Transport-Security
Value : max-age=315360000; includeSubDomains; preload

Key   : ATL-TraceId
Value : 3e5b272337f1268e

Key   : X-AACCOUNTID
Value : 557058%3A74595148-5c8d-43c6-a9c3-adef4db3aa74

Key   : X-AREQUESTID
Value : da700b67-538e-457a-ba04-8260362368ad

Key   : X-XSS-Protection
Value : 1; mode=block

Key   : Transfer-Encoding
Value : chunked

Key   : Timing-Allow-Origin
Value : *

Key   : X-AUSERNAME
Value : david.hromyk

Key   : X-Content-Type-Options
Value : nosniff

Key   : Connection
Value : keep-alive

Key   : X-Seraph-LoginReason
Value : OK

Key   : Warning
Value : 299 Jira "The 'permissions' query parameter is required. Not sending it is 
        deprecated and will be disallowed in the future. (Deprecation start date: 
        August 1, 2018)"

Key   : Cache-Control
Value : no-cache, no-store, no-transform

Key   : Content-Type
Value : application/json;charset=UTF-8

Key   : Date
Value : Fri, 26 Apr 2019 20:13:48 GMT

Key   : Set-Cookie
Value : atlassian.xsrf.token=BOAY-UGQ8-ODJ6-T752_31542822829005ac7a9fed2b720b6e3809149db
        6_lin; Path=/; Secure

Key   : Server
Value : AtlassianProxy/1.13.6.2

Here is my coworkers:


PS C:\Users\millie.mulka>> $webResponse;$webResponse.headers

IsMutuallyAuthenticated : False
Cookies                 : {}
Headers                 : {Strict-Transport-Security, ATL-TraceId, X-AREQUESTID, X-XSS-Protection...}
SupportsHeaders         : True
ContentLength           : -1
ContentEncoding         :
ContentType             : text/html;charset=UTF-8
CharacterSet            : UTF-8
Server                  : AtlassianProxy/1.13.6.2
LastModified            : 4/26/2019 1:08:54 PM
StatusCode              : Unauthorized
StatusDescription       :
ProtocolVersion         : 1.1
ResponseUri             : https://faithlife.atlassian.net/rest/api/2/mypermissions?maxResults=25
Method                  : GET
IsFromCache             : False

Strict-Transport-Security
ATL-TraceId
X-AREQUESTID
X-XSS-Protection
Transfer-Encoding
Timing-Allow-Origin
X-Content-Type-Options
Connection
X-Seraph-LoginReason
Content-Type
Date
Server
WWW-Authenticate
lipkau commented 5 years ago

just to make sure: pick a ticket you know millie can open and try

Get-JiraIssue ABC-1234 -Cred $cred

I imagine it will also return 401. not much I can help you with. this part of the code is pretty well tested and I don't know your system to help you to debug. first google result is https://community.atlassian.com/t5/Jira-questions/JIRA-Rest-API-authentication-always-returns-401-unauthorized/qaq-p/187181

DavidHromyk commented 5 years ago

Same result

PS C:\Users\david.hromyk> Add-JiraUser
cmdlet Add-JiraUser at command pipeline position 1
Supply values for the following parameters:
Firstname: Tim
Lastname: Bim
Invoke-JiraMethod : The user could not be authenticated.
At C:\Users\david.hromyk\Documents\WindowsPowerShell\Modules\JiraPS\2.10.3\JiraPS.psm1:3676 
char:19
+         $result = Invoke-JiraMethod @parameter
+                   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : AuthenticationError: (:) [Invoke-JiraMethod], HttpRequestException
    + FullyQualifiedErrorId : AuthenticationFailed,Invoke-JiraMethod

I created a new admin user to test this and unfortunately the exact same is happening. I am completely stumped at this point. I don't understand what the difference would be between myself or any of the other users. As far as those comments go, we are using the correct usernames and have tried multiple. Not sure if there is a permission specifically need on the Jira end of things?

DavidHromyk commented 5 years ago

Odd but this was resolved by using their API key's as the password with their email address https://confluence.atlassian.com/cloud/api-tokens-938839638.html. I did find this wasn't related to this module at all as I was getting the same results with:

    function ConvertTo-Base64($string) {
    $bytes  = [System.Text.Encoding]::UTF8.GetBytes($string);
    $encoded = [System.Convert]::ToBase64String($bytes);
    return $encoded;
}

function Get-HttpBasicHeader($Headers = @{}) {
    $credentials = Get-Credential 
    [string]$username = $credentials.UserName
    [string]$password = $credentials.GetNetworkCredential().Password
    $b64 = ConvertTo-Base64 "$($username):$($Password)"
    $Headers["Authorization"] = "Basic $b64"
    $Headers["X-Atlassian-Token"] = "nocheck"
    return $Headers
}

$header = Get-HttpBasicHeader 

Thanks for the prompt responses! I am still not quite sure why, but it looks like there is an issue with how credentials are passed over to the rest API with basic auth. I will reach out to Atlassian to see if I can figure out what exactly is happening.

lipkau commented 5 years ago

Hi @DavidHromyk

I am glad you figured it out. I should have been able to tell you that based on your baseUrl, as it was me who wrote the help on that. https://atlassianps.org/docs/JiraPS/about/authentication.html#api-token

🤷‍♂ sorry about that

sgtwilko commented 4 years ago

For people from the future who also have this issue...

Jira has a bug where password & usernames that have unicode/special characters cause the authentication to fail only on the REST API.

see https://jira.atlassian.com/browse/JRASERVER-59828

and

https://community.atlassian.com/t5/Jira-questions/Basic-Authentication-problem-with-special-character-in-password/qaq-p/1008388