GetAccessToken.ps1


<#PSScriptInfo
 
.VERSION 1.0
 
.GUID 22a4ed59-2afd-47fe-a9e9-900f9931a75b
 
.AUTHOR nali2
 
.COMPANYNAME
 
.COPYRIGHT
 
.TAGS
 
.LICENSEURI
 
.PROJECTURI
 
.ICONURI
 
.EXTERNALMODULEDEPENDENCIES
 
.REQUIREDSCRIPTS
 
.EXTERNALSCRIPTDEPENDENCIES
 
.RELEASENOTES
 
 
#>


<#
 
.DESCRIPTION
 test to ps
 
#>
 

Param()


function Get-TokenProperties
{
    Param
    (
        [Parameter(Mandatory=$false)]
        [ValidateNotNullOrEmpty()]
        [String]
        $AccessToken
    )
    
    #Write-output $AccessToken
    Write-output "Access Token can be printed"
}

$connectionName = "AzureRunAsConnection"
try
{
    # Get the connection "jason "
    $servicePrincipalConnection=Get-AutomationConnection -Name $connectionName         

    "Logging in to Azure..."
    Add-AzureRmAccount `
       -ServicePrincipal `
       -TenantId $servicePrincipalConnection.TenantId `
       -ApplicationId $servicePrincipalConnection.ApplicationId `
       -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint

       $null = Select-AzureRmSubscription -SubscriptionId 0124826c-f043-4343-aebd-bd93e8e4a7b7
}
catch {
   if (!$servicePrincipalConnection)
   {
      $ErrorMessage = "Connection $connectionName not found."
      throw $ErrorMessage
  } else{
      Write-Error -Message $_.Exception
      throw $_.Exception
  }
}
$azureRMProfile = Get-Module -ListAvailable -Name AzureRM.Profile | Select Name, Version, Path
$azureRMProfile | fl *
if ($azureRMProfile.Version.ToString() -eq "1.0.3")
{
    $azureEnvironment =  Get-AzureRmEnvironment -Name 'AzureCloud'
    $applicationId = $servicePrincipalConnection.ApplicationId
    $tenantId = $servicePrincipalConnection.TenantId
    $authority = $azureEnvironment.ActiveDirectoryAuthority + $tenantId + "/oauth2/authorize"
    $resourceAppIdURI = $azureEnvironment.ResourceManagerUrl

    # Get the Run As Account cert
    Write-output "Get the Run As Account cert"
    $runAsCert = Get-AutomationCertificate -Name "AzureRunAsCertificate"
    $password = [System.Web.Security.Membership]::GeneratePassword(10,2)
    $cert = $runAsCert.Export("pfx",$password)
    $x509KeyStorageFlags = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet
    $exportedCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2($cert, $password, $x509KeyStorageFlags)

    $modulePath = Split-Path -Parent $azureRMProfile.Path
    Add-Type -Path (Join-Path $modulePath "Microsoft.IdentityModel.Clients.ActiveDirectory.dll")

    # Get the Bearer token
    Write-output "Get the Bearer token"
    $clientAssertionCertificate = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate($applicationId, $exportedCert)
    $authenticationContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext($authority, $false)
    $authResult = $authenticationContext.AcquireTokenAsync($resourceAppIdURI, $clientAssertionCertificate)
    $result = $authResult.Result
    #$result | fl *
    $token = $result.AccessToken
}
else
{
    $context = Get-AzureRmContext
    $cache = $context.TokenCache
    if(-not $cache)
    {
        Write-output "Token Cache is null"
    }
    else
    {
        $cacheItem = $cache.ReadItems()
        $cacheItem | fl *
        $token = $cacheItem.AccessToken
    }
}
if($token)
{
    #Write-output "Access Token found"
    Write-output "type of Token: $($token.Gettype())"
    if($($token.Gettype()) -eq [String])
    {
        Write-output "length of token: $($token.Length)"
    }
    Get-TokenProperties -AccessToken $token
}
else
{
    Write-output "Access Token Not Found"
}