Examples/Authentication.ps1

#Requires -Modules PartnerCustomerCommunity
# Import-Module .\ -Force
# Import-Module ..\ -Force

# Create a web app (admin user -> web app) #
# Done once.
$WebApp = New-PartnerWebApp -DisplayName ('Test ' + (Get-Date -Format s)) -IsFallbackPublicClient #-StayConnected
Write-Warning ('Remember to update the WebApp secret on {0}.' -f $WebApp.SecretExpiration)

# Get an authorization code (web app -> authorization code) #
# Get a refresh token (authorization code -> refresh token) #
# Need to be done once, or if the refresh token was not used for 90 days and expired.
# Will throw an error if `New-PartnerWebApp` was run recently so I added retry/sleep logic:
try {
    $RefreshToken = $null
    $Stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
    do {
        try {
            $RefreshToken = New-PartnerRefreshToken -ApplicationId $WebApp.Credential.UserName
        }
        catch {
            if ($Stopwatch.Elapsed.Minutes -ge 2) {
                throw $_
            }
            if ($_ -like '*AADSTS50059*' -or $_ -like '*AADSTS700016*') {
                Write-Warning ('WebApp not created yet, elapsed {0}, retrying...' -f $Stopwatch.Elapsed.ToString())
                Start-Sleep -Seconds 5
            }
            else {
                throw $_
            }
        }
    } until ($RefreshToken)
}
finally {
    $Stopwatch.Stop()
}

# Get an access token (refresh token -> access token) #
# Connecting will do this automatically (it will also regenerate a new RefreshToken when needed automatically):
Connect-PartnerCenter -Credential $WebApp.Credential -RefreshToken $RefreshToken -Tenant $WebApp.Tenant
# Alternatively can be generated by:
New-PartnerAccessToken -Credential $WebApp.Credential -RefreshToken $RefreshToken -Tenant $WebApp.Tenant

# Make a Partner Center API call #
# For example:
Get-PartnerOrganizationProfile