使用 user/password 连接到 TFS 时出现问题

Problem to connect to TFS with user/password

当我尝试连接到 tfs 时,函数 Get-Data 失败并出现 401 错误,尽管函数 Get-DataWithCred 以相同的参数成功。

不明白这两者的区别?

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
}

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

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

$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

您需要使用微软的方式来传递您的凭据:ntlm 协议。

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

一个简单的例子:

import os
import requests
from requests_ntlm import HttpNtlmAuth


def main():
    user = "user"
    password = "password"

    session = requests.Session()
    session.auth = HttpNtlmAuth(user, password)

    url = "https://tfs-url.com"

    response = session.get(url)

    print(response)


if __name__ == "__main__":
    main()