lwhitelock / HuduM365Automation

Hudu Microsoft 365 Syncronisation Tool
GNU Affero General Public License v3.0
29 stars 72 forks source link

Handle exchange authentication errors #2

Closed JoranSlingerland closed 2 years ago

JoranSlingerland commented 2 years ago

Right now if the script is unable to authenticate to exchange the script will error out completely even though exchange is not required for most requests / stats.

The pull requests makes sure that if there are any issues it will still run everything else.

main error I was running in that is fixed now:

Invoke-RestMethod : {"error":"invalid_resource","error_description":"AADSTS500014: The service principal for resource 'https://outlook.office365.com' is disabled. This indicate that a
subscription within the tenant has lapsed, or that the administrator for this tenant has disabled the application, preventing tokens from being issued for it.\r\nTrace ID:
8fd8421c-4adc-405f-92f9-f2bd61326000\r\nCorrelation ID: 46d130f0-2301-45c2-9b6b-e848bc7502b9\r\nTimestamp: 2022-02-03 11:11:23Z","error_codes":[500014],"timestamp":"2022-02-03
11:11:23Z","trace_id":"8fd8421c-4adc-405f-92f9-f2bd61326000","correlation_id":"46d130f0-2301-45c2-9b6b-e848bc7502b9"}

The code it is quite simple it splits up

$ExchangeAuthHeaders = Get-GraphToken -AppID 'a0c73c16-a7e3-4564-9a95-2bdf47383716' -RefreshToken $env:ExchangeRefreshToken -Scope 'https://outlook.office365.com/.default' -Tenantid $TenantFilter

and

$Authheaders = Get-GraphToken -tenantid $TenantFilter

in two seperate try catch statements

if the exchange auth fails it will set $ExchangeAuthenticated to $false. $ExchangeAuthenticated is then wrapped around all statements that need exchange with a if statement so they get skipped if it is set to $false.

As side note, Really like the project!