Forum Discussion

paulsmith145's avatar
paulsmith145
Copper Contributor
Jun 27, 2025

Handling user cancellation of authorization

My Winforms app has the code below, which pops up a browser page prompting the user to log on to his or her Office 365 account.  If the user cancels the log-in by shutting down the browser page, the app crashes - the Winforms interface just disappears, and it does not display any of the error messages in the catch blocks.   If I remove the exception handling, and the user cancels the authorization, the app just hangs - presumably because it is awaiting something that never happens.  I need to be able to return to the app without crashing it if the user cancels the log-in.  Evidently the cancellation causes some exceptiont that I am not handling. I'd appreciate any suggestions.  Thanks in advance.

public static async void initializeGraphAsync()
{
    string[] scopes = { "User.Read", "Notes.Create", "Notes.ReadWrite", "Tasks.Read", "Tasks.ReadWrite", "MailboxSettings.ReadWrite" };

    InteractiveBrowserCredentialOptions options = new()
    {
        TenantId = "common",
        ClientId = "[client id]", 
        AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
        RedirectUri = new Uri("http://localhost"),
    };

    try
    {
        _credential = new InteractiveBrowserCredential(options);
        _client = new GraphServiceClient(_credential, scopes);

        user = await _client..GetAsync((config) =>  //My code has "Me" between the periods here, but when I try to post this with the "Me" I get an error message "t[dot]Me is not allowed in this forum".
        {
           config.QueryParameters.Select = new[] { "displayName", "mail", "userPrincipalName" };
        });
        
        if (user == null)
        {
             throw new TaskCanceledException("User authentication was canceled or failed.");
        }
    }

    catch (OperationCanceledException ex)
    {
        MessageBox.Show("Authentication was canceled or failed: " + ex.Message);
    }
    
    catch (Exception e)
    {
        MessageBox.Show("Error initializing Graph: " + e.Message);
    }

}

No RepliesBe the first to reply

Resources