Access ASANA via windows powershell using APIKEY

2019-06-14 13:05发布

I have created this following two codes in powershell to access ASANA.

But both of them dont work. I always get this error

"The remote server returned an error: (401) Unauthorized."

Any help appreciated. If you have a working C# code that can connect to any secure server with only APIKey, please post it. I could convert it to powershell code.

Code 1

Function Get-WebResponseString
{
    param (
        [Parameter(Mandatory=$true)]
        [String]$Url,       
        [Parameter(Mandatory=$true)]
        [String]$Method,
        [Parameter(Mandatory=$false)]
        [System.Net.NetworkCredential]$Credential
    )

    $Request = [System.Net.WebRequest]::Create($Url)    
    $Request.Method = $Method
    $Request.ContentType = "application/x-www-form-urlencoded";
    if ($Credential -ne $null)
    {
        $Request.Credentials = $credential
        write-host "****" -foregroundcolor blue
    }

    $Response = $Request.GetResponse()

    $StreamReader = New-Object System.IO.StreamReader $Response.GetResponseStream()
    $StreamReader.ReadToEnd()
} 

$Url = "https://app.asana.com/api/1.0/tasks"
$Username = "MMuthusamy@xxxxxx.xom"
$apikey="xxxxxxxxx"

$credential = New-Object System.Net.NetworkCredential @($Username, $apikey)   

Get-WebResponseString -Url $Url -Credential $credential -Method "GET" 

Code 2

$sha = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider 

$apikey="xxxxxxx"
#Add colon
$authinfo=$apikey+":";
$string1 = $authinfo
Write-Host $string1  -ForeGroundColor Green

#Encoding format
$enc = [system.Text.Encoding]::UTF8

#get bytes
$data1 = $enc.GetBytes($string1) 

#Encode
$result1 = $sha.ComputeHash($data1)

#convert to 64 bit
$mykey=[System.Convert]::ToBase64String($result1)

Write-Host $mykey -ForeGroundColor Green

$url = "https://app.asana.com/api/1.0/tasks"
$url="https://app.asana.com/api/1.0/users"
$request = [System.Net.WebRequest]::Create($url)
$authorization = "Authorization: Basic " + $myKey
Write-Host $authorization -ForeGroundColor Green

$request.Headers.Add($authorization)
#$request.Headers.Add("Authorization: BASIC $mykey")
$response = $request.GetResponse()
Write-Host $Response  -ForeGroundColor Green 

标签: api-key asana
1条回答
老娘就宠你
2楼-- · 2019-06-14 13:42

(I work at Asana)

The 401 header is a clue that the problem lies somewhere in your authorization header.

The HTTP Basic Auth spec does not call for a SHA1 hash of the username:password. It's just straight base64 encoding of that string. Try passing $authinfo to your call to ToBase64String instead of hashed data.

查看更多
登录 后发表回答