【问题标题】:Problem to connect to TFS with user/password使用用户/密码连接到 TFS 的问题
【发布时间】:2019-08-14 06:12:51
【问题描述】:

当我尝试连接到 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 脚本连接,当我使用 requests 库时,它的失败方式与函数 Get-Data 相同。

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

【问题讨论】:

    标签: rest powershell tfs tfs-2015


    【解决方案1】:

    $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

    代码 sn-p:

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

    【讨论】:

    • 谢谢,但它没有回答我的问题,您的方法与我的函数 Get-DataWithCred 相同。而且我不能在powershell的其他语言中使用这种方法:(
    • 所以你想通过python连接tfs api?
    • 是的,抱歉我的问题不是很容易理解。我编辑了它。
    【解决方案2】:

    您需要使用微软的方式来传递您的凭据: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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-21
      • 2017-04-07
      • 2021-01-21
      • 2019-05-08
      相关资源
      最近更新 更多