How to get auth token bearer via powershell cmdlet?

1.8k Views Asked by At

I need to add an auth bearer to requests I make to an API. I have done this in C# but need to do it via powershell. I tried turning my C# method to a cmdlet like this:

[Cmdlet(VerbsCommunications.Get, "Token")]
public class GetAuthTokenCommand : Cmdlet
{
    // Overide the ProcessRecord method
    protected override void ProcessRecord()
    {
        AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/blablaguid/oauth2/token");
        Task<AuthenticationResult> resultTask = authContext.AcquireTokenAsync(
            "MyResourceUri",
            "MyClientId",
            new Uri("https://login.live.com/oauth20_desktop.srf"),
            new Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters(PromptBehavior.Auto, false));

        resultTask.Wait();

        WriteObject("Token: "+ resultTask.Result.AccessToken);
    }
}

However, this gives me an error:

+ CategoryInfo          : NotSpecified: (:) [Send-Greeting], AggregateException
+ FullyQualifiedErrorId : System.AggregateException,GetAuthtoken.SendGreetingCommand

Any ideas?

1

There are 1 best solutions below

1
On
function GetAuthToken
{
    param
    (
            [Parameter(Mandatory=$true)]
            $ApiEndpointUri,

            [Parameter(Mandatory=$true)]
            $AADTenant
    )
    $adal = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\" + `
                "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
    $adalforms = "${env:ProgramFiles(x86)}\Microsoft SDKs\Azure\PowerShell\ServiceManagement\Azure\Services\" + `
                    "Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"

    [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
    [System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null

    $clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
    $redirectUri = "urn:ietf:wg:oauth:2.0:oob"
    $authorityUri = “https://login.windows.net/$aadTenant”

    $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authorityUri

    $authResult = $authContext.AcquireToken($ApiEndpointUri, $clientId,$redirectUri, "Auto")

    return $authResult
}

$ApiEndpointUri = "https://management.azure.com/" #change this to graph api uri
$AADTenant = 'GUID' #AAD tenant guid
$token = GetAuthToken -ApiEndPointUri $ApiEndpointUri -AADTenant $AADTenant
$header = @{
    'Content-Type'='application\json'
    'Authorization'=$token.CreateAuthorizationHeader()
}

$request = ``
(Invoke-RestMethod -Uri $request -Headers $header -Method Get).value

I've took this sometime ago from somewhere on the web (can't recall where) it works for querying Azure REST\Graph Api.