当我尝试连接到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
您需要使用microsoft方式传递凭证: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()