Azure automation - authentication API permissions

By using app registration you can assign granular API permissions. It should start from

And to allow your automation to e.g. read users from Azure AD you need to grant: User.Read and User.Read.All

 

Then on Certificates & secretes (visible on above screenshot) you create new secret (copy it as it is shown only once) which is valid for 1 year.

 

On specific azure automation account go to variables now:

And create new variable – mark it as encrypted and in the value of it (string) paste copied secret. Now in a runbook created under this automation account you can use:

$cSec = Get-AutomationVariable -Name 'clientSecretForSDtoolbox'

To get value of this secret.  Below code is an example how to authenticate. Client_ID within Body is the application ID of app registration

 

 

Function Get-GraphAccessToken{

    $Body = @{

        Grant_Type    = "client_credentials"

        Scope         = "https://graph.microsoft.com/.default"

        client_Id     = "xxx"

        Client_Secret = $cSec

    }

    $authResult = ConvertFrom-Json(Invoke-WebRequest -Method "POST" -uri "https://login.microsoftonline.com/tenantID/oauth2/v2.0/token" -ContentType 'application/x-www-form-urlencoded' -Body $Body).Content

    $TokenRenewalTime = (Get-Date).AddMinutes(55)

    # Put token in to a nice format

    if ($authResult.access_token) {

        $private:authHeader = @{

            'Content-Type'  = 'application/json'

            'Authorization' = "Bearer " + $authResult.access_token

            'ExpiresIn'     = $authResult.expires_in

            'TimeToRenew'   = $TokenRenewalTime

        }

        # Return token

        return $authHeader

    }

    else {

        return "ErrorAPIToken: $authResult"

    }

}

$token = Get-GraphAccessToken

$UserInfo = 'https://graph.microsoft.com/v1.0/users/xxx

Invoke-RestMethod -Method Get -Uri $UserInfo -Headers @{Authorization = $Token.Authorization}

Komentarze