使用用户/密码连接到TFS的问题

时间:2019-03-23 11:57:30

标签: rest powershell tfs tfs2015

当我尝试连接到tfs时,尽管Get-DataWithCred函数使用相同的参数成功,但Get-Data函数失败并显示401错误。

不明白这两者的区别吗?

function Get-Data([string]$username, [string]$password, [string]$url) 
{
  # Step 1. Create a username:password pair
  $credPair = "$($username):$($password)"

  # Step 2. Encode the pair to Base64 string
  $encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($credPair))

  # Step 3. Form the header and add the Authorization attribute to it
  $headers = @{ Authorization = "Basic $encodedCredentials" }

  # Step 4. Make the GET request
  $responseData =  Invoke-WebRequest -Uri $url -Method Get -Headers $headers
  return $responseData
}


function Get-DataWithCred([string]$username, [string]$password, [string]$url) 
{
  $p = ConvertTo-SecureString -String $password -AsPlainText -Force

  $Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $p

  $responseData =  Invoke-WebRequest -Uri $url -Method Get  -Credential $Cred
  return $responseData
}

目的也是通过python脚本通过tfs进行连接,当我使用请求库时,python脚本与Get-Data函数失败的方式相同。

>>> r = requests.get('https://tfs-url.com', auth=('user', 'pass'))
>>> r.status_code
401

2 个答案:

答案 0 :(得分:0)

$ encodedCredentials好像有问题。

看看Choosing the right authentication mechanism

对于连接到TFS的脚本,我使用以下代码:

     $strUser = 'domain\userID'
     $password = "YOURPASSWORD"
     $strPass = ConvertTo-SecureString -String $password -AsPlainText -Force
     $cred= New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($strUser, $strPass)

然后像您一样连接到TFS:

$responseData =  Invoke-WebRequest -Uri $url -Method Get  -Credential $cred

或者,如果您希望与运行脚本的用户连接到TFS,则可以使用

-UseDefaultCredentials

代码段:

$responseData =  Invoke-WebRequest -Uri $url -Method Get  -UseDefaultCredentials

答案 1 :(得分:0)

您需要使用Microsoft方式来传递您的证书:ntlm协议。

默认情况下,请求不支持此协议,但是库requests_ntlm通过添加对ntlm的支持来扩展请求。

一个简单的例子:

initAssets