Search code examples
c#powershellazureazure-active-directoryaccess-token

Get Azure Active Directory Access Token from Powershell


I have an Application Id and a Key that I generated in the Azure portal after registering an Azure Active Directory Application.

With this pair and from my Powershell script, I would like to generate an Access Token that I will use in my script in a HTTP Request.

I am able to get an access token using C# (see below code) but I am not sure how to do something similar in Powershell. Is there anything already built in Powershell? If not, can someone point me to a solution? I am pretty sure I am not the only person with this question.

public static async Task<string> GetAccessTokenAsync(string clientId, string appKey, string resourceId)
{
     string aadInstance = "https://login.microsoftonline.com/{0}";
     string tenant = "<TENANT>.onmicrosoft.com";
     string authority = string.Format(CultureInfo.InvariantCulture, aadInstance, tenant);
     AuthenticationContext authContext = new AuthenticationContext(authority);
     ClientCredential clientCredential = new ClientCredential(clientId, appKey);

     AuthenticationResult authenticationResult = null;       
     authenticationResult = await authContext.AcquireTokenAsync(resourceId, clientCredential);

     return authenticationResult.AccessToken;
}

Solution

  • I wrote what I consider to be a great tutorial on just this:

    Azure AD Authentication with PowerShell and ADAL

    With these scripts, you can get authentication and REST API calls done with as little as 13 lines of PowerShell. Running the code is instant, and modifying the REST calls or even the authentication parameters takes seconds rather than minutes.

    You can find all my scripts on GitHub here.

    The trick is that you can actually load the .NET assemblies of ADAL using PowerShell's Add-Type function:

    # Load ADAL
    Add-Type -Path ".\ADAL\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"\
    

    From there, calling all the ADAL functions is as simple as in a standard C# application.

    That being said, the other thing you may want to look into is the official AAD PowerShell Module:

    Azure Active Directory PowerShell Version 2

    You can use the Azure Active Directory PowerShell Module Version 2 for Azure AD administrative tasks such as user management, domain management and for configuring single sign-on.

    Depending on your exact needs here, one of these two options should work for you. Let me know if this helps!