使用PowerShell使用GitHub Api进行基本身份验证

Sha*_*tin 4 powershell github basic-authentication github-api

我一直在尝试使用带有PowerShell 的GitHub Api进行基本身份验证.以下不起作用:

 > $cred = get-credential
 # type username and password at prompt

 > invoke-webrequest -uri https://api.github.com/user -credential $cred

 Invoke-WebRequest : {
     "message":"Requires authentication",
     "documentation_url":"https://developer.github.com/v3"
 }
Run Code Online (Sandbox Code Playgroud)

我们如何使用PowerShell与GitHub Api进行基本身份验证?

Mat*_*sen 13

基本身份验证基本上要求您Authorization使用以下格式在标头中发送凭据:

'Basic [base64("username:password")]'
Run Code Online (Sandbox Code Playgroud)

在PowerShell中,它将转换为:

function Get-BasicAuthCreds {
    param([string]$Username,[string]$Password)
    $AuthString = "{0}:{1}" -f $Username,$Password
    $AuthBytes  = [System.Text.Encoding]::Ascii.GetBytes($AuthString)
    return [Convert]::ToBase64String($AuthBytes)
}
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

$BasicCreds = Get-BasicAuthCreds -Username "Shaun" -Password "s3cr3t"

Invoke-WebRequest -Uri $GitHubUri -Headers @{"Authorization"="Basic $BasicCreds"}
Run Code Online (Sandbox Code Playgroud)