首页 > 解决方案 > 如果从 c# 执行,则使用 PowerShell 脚本获取 Azure DevOps 的不完整或部分访问令牌

问题描述

我正在使用 PowerShell 访问 Azure DevOps 访问令牌,因为我没有字符串格式的 PAT。我正在使用 WPF 开发基于桌面的应用程序,并从此 WPF 应用程序运行以下 PowerShell 脚本。它成功执行,但给了我一个长度为 1289 个字符的部分或不完整的访问令牌。如果我直接在 PowerShell ISE 上运行相同的脚本,那么它会提供长度为 2126 个字符的完整访问令牌。

访问令牌的 PS 脚本

param (
    [string]
    $applicationid,
    [string]
    $secretKey,
    [string]
    $tenantID,
    [string]
    $subscriptionId
)

Clear-AzureRmContext -Force;
$password = ConvertTo-SecureString -String $secretKey -AsPlainText -Force;
$cred = New-Object System.Management.Automation.PSCredential($applicationid,$password);
Connect-AzureRmAccount -ServicePrincipal -Credential $cred -Tenant $tenantID;

Select-AzureRmSubscription -SubscriptionId $subscriptionId
$currentAzureContext = Get-AzureRmContext;
$azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile;
$profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile);
$pat = $profileClient.AcquireAccessToken($currentAzureContext.Subscription.TenantId).AccessToken;
Write-Output $pat

C#代码如下

 var fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "myAppFolder", "Script.ps1");
 string scriptpath = fileName + " -applicationid " + thisApp.xmlSettings.ClientId + " -secretKey " + thisApp.xmlSettings.ClientKey + " -tenantID " + thisApp.xmlSettings.TenantId + " -subscriptionId " + thisApp.xmlSettings.SubscriptionId + "";
 PowerShell psExec = PowerShell.Create();
 psExec.AddScript(scriptpath);
 psExec.AddCommand("out-string");
 StringBuilder sb = new StringBuilder();
 Collection<PSObject> results;
 Collection<ErrorRecord> errors;
 results = psExec.Invoke();
 errors = psExec.Streams.Error.ReadAll();

 if (errors.Count > 0)
 {
      foreach (ErrorRecord error in errors)
      {
           sb.AppendLine(error.ToString());
      }
 }
 else
 {
     foreach (PSObject result in results)
     {
         string[] token = result.BaseObject.ToString().Split(new char[] { '\n' });
         thisApp.staticAccessToken = token[14].ToString();
     }
}

请纠正我做错的地方。如果我有一个长度为 2126 个字符的访问令牌,我可以使用 Azure DevOps 的 REST API,如果我的访问令牌的长度是 1289,我会得到 404。

标签: c#wpfpowershellazure-active-directoryaccess-token

解决方案


推荐阅读