Reputation: 3965
I need to add an authorization token to a request I'm making via powershell. In c#, I can get the token like this:
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;
}
How would I do this in powershell? I need to get that token to add as a header:
Authorization: Bearer blahblahblahtokenblahblah
Upvotes: 0
Views: 2675
Reputation: 5747
Try run the following code in 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
From: https://gallery.technet.microsoft.com/scriptcenter/Easily-obtain-AccessToken-3ba6e593
Upvotes: 1
Reputation: 5085
You can do like this.
$bearerAuthValue = "Bearer {token}"
$headers = @{ Authorization = $bearerAuthValue }
Invoke Web Request like this
Invoke-WebRequest -uri "https://api.google.com/user" -Headers $headers
You can find further info here https://foxdeploy.com/2015/11/02/using-powershell-and-oauth/
Upvotes: 0