Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Break statements after warnings in Get-MSIntuneAuthToken makes it impossible for consumers to handle errors #32

Open
onerstam opened this issue Aug 27, 2021 · 0 comments

Comments

@onerstam
Copy link

The use of a break statement after Write-Warning, when not in a loop, will case also consumers of this commandlet to exit execution. See https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_break?view=powershell-7.1 section Do not use break outside of a loop, switch, or trap

Write-Warning -Message "Failure to acquire access token. Response with access token was null"; break

Below is with context in PSIntuneAuth.psm1

# Check if access token was acquired
if ($AuthenticationResult.AccessToken -ne $null) {
    Write-Verbose -Message "Successfully acquired an access token for authentication"

    # Construct authentication hash table for holding access token and header information
    $Authentication = @{
        "Content-Type" = "application/json"
        "Authorization" = -join("Bearer ", $AuthenticationResult.AccessToken)
        "ExpiresOn" = $AuthenticationResult.ExpiresOn
    }
    # Return the authentication token
    return $Authentication
}
else {
    Write-Warning -Message "Failure to acquire access token. Response with access token was null"; break
}

This isssue can be seen using a script like this.

$Tenant = "sometenant.onmicrosoft.com"
[securestring]$password = ConvertTo-SecureString "AlwaysWr0ng!" -AsPlainText -Force
[pscredential]$credentials = New-Object System.Management.Automation.PSCredential ("[email protected]", $password)

Write-Host "Getting the AuthToken ..."
$Global:AuthToken = Get-MSIntuneAuthToken -TenantName $Tenant -Credential $credentials 
Write-Host "This will never be executed ... "

This would be better implemented with this pattern:

else {
    Write-Warning -Message "Failure to acquire access token. Response with access token was null"; 
    return $null
}
onerstam added a commit to onerstam/Intune that referenced this issue Aug 27, 2021
Break statements can cause callers to exit execution when placed outside of a loop, switch, or trap. Resolves issue MSEndpointMgr#32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant