如何通过powershell获取authtoken请求

时间:2016-11-22 21:14:52

标签: c# powershell http httpwebrequest

我需要为我通过powershell制作的请求添加授权令牌。在c#中,我可以得到这样的令牌:

private static string GetAccessToken()
    {
        AuthenticationContext authContext = new AuthenticationContext(((MyApp)Application.Current).AuthorityAddress);
        Task<AuthenticationResult> resultTask = authContext.AcquireTokenAsync(
            (myAuthServerAddress,
            clientId,
            redirectUri,
            new Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters(PromptBehavior.Auto, false));

        resultTask.Wait();
        return resultTask.Result.AccessToken;
    }

我如何在powershell中执行此操作?我需要将该标记添加为标题:

Authorization: Bearer blahblahblahtokenblahblah

2 个答案:

答案 0 :(得分:1)

尝试在PowerShell中运行以下代码:

function Get-AzureRmCachedAccessToken()
{
  $ErrorActionPreference = 'Stop'

  if(-not (Get-Module AzureRm.Profile)) {
    Import-Module AzureRm.Profile
  }
  $azureRmProfileModuleVersion = (Get-Module AzureRm.Profile).Version
  # refactoring performed in AzureRm.Profile v3.0 or later
  if($azureRmProfileModuleVersion.Major -ge 3) {
    $azureRmProfile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
    if(-not $azureRmProfile.Accounts.Count) {
      Write-Error "Ensure you have logged in before calling this function."    
    }
  } else {
    # AzureRm.Profile < v3.0
    $azureRmProfile = [Microsoft.WindowsAzure.Commands.Common.AzureRmProfileProvider]::Instance.Profile
    if(-not $azureRmProfile.Context.Account.Count) {
      Write-Error "Ensure you have logged in before calling this function."    
    }
  }

  $currentAzureContext = Get-AzureRmContext
  $profileClient = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($azureRmProfile)
  Write-Debug ("Getting access token for tenant" + $currentAzureContext.Subscription.TenantId)
  $token = $profileClient.AcquireAccessToken($currentAzureContext.Subscription.TenantId)
  $token.AccessToken
}

Get-AzureRmCachedAccessToken

来自:https://gallery.technet.microsoft.com/scriptcenter/Easily-obtain-AccessToken-3ba6e593

答案 1 :(得分:0)

你可以这样做。

$bearerAuthValue = "Bearer {token}"

$headers = @{ Authorization = $bearerAuthValue }

像这样调用Web请求

Invoke-WebRequest -uri "https://api.google.com/user" -Headers $headers

您可以在https://foxdeploy.com/2015/11/02/using-powershell-and-oauth/

找到更多信息