Demonstrates how to get a Microsoft Dynamics CRM OAuth2 access token from a desktop (installed) application or script.
# This should be the port in the localhost redirect URL for your app.
# is exactly "http://localhost:3017/".  Don't forget the ending "/" char.
# The redirect URL would look like "http://localhost:3017/" if the port number is 3017.
# Get the endpoints from the Azure Portal in the "endpoints" section of App Registrations..
# Replace these with actual values.
$oauth2.RedirectAllowHtml = "<html><body><p>Thank you for granting access.</p></bod></html>"
$oauth2.RedirectDenyHtml = "<html><body><p>Maybe next time...</p></bod></html>"
# Begin the OAuth2 three-legged flow.  This returns a URL that should be loaded in a browser.
# We can pre-check the URL by sending a GET to catch any up-front errors.
# If we receive JSON with an error in response, then we don't proceed any farther.
# If we receive an HTML response, and the response status = 200, then all should be OK.
# We can proceed by displaying an interactive browser loaded with the url.
# If the HTTP request itself failed, then examine the error.
# OK.. the pre-flight check seems OK, go ahead with getting the interactive user authorization..
# At this point, your application should load the URL in a browser.
# The GitHub account owner would interactively accept or deny the authorization request.
# Now wait for the authorization.
# We'll wait for a max of 30 seconds.
# the AuthFlowState will be equal to 1 or 2.
# 1: Waiting for Redirect. The OAuth2 background thread is waiting to receive the redirect HTTP request from the browser.
# 2: Waiting for Final Response. The OAuth2 background thread is waiting for the final access token response.
# In that case, cancel the background task started in the call to StartAuth.
# 3: Completed with Success. The OAuth2 flow has completed, the background thread exited, and the successful JSON response is available in AccessTokenResponse property.
# 4: Completed with Access Denied. The OAuth2 flow has completed, the background thread exited, and the error JSON is available in AccessTokenResponse property.
# 5: Failed Prior to Completion. The OAuth2 flow failed to complete, the background thread exited, and the error information is available in the FailureInfo property.
# getting the current system date/time and adding the "expires_in" seconds.
# This way we'll know when the token expires.
# Save the JSON to a file for future requests.