How can I redirect the user to the internet to complete authentication and persist the token?

ChuckieAJ 316 Reputation points
2024-04-04T16:12:53.7366667+00:00

I am trying to add authentication to my app for Microsoft Graph and I have made some progress with this. I followed this tutorial and I have it working.

But, this is how it is asking the user to authenticate at the moment:

        void InitializeGraph(Settings settings)
        {
            GraphHelper.InitializeGraphForUserAuth(settings,
                (info, cancel) =>
                {
                    // Display the device code message to
                    // the user. This tells them
                    // where to go to sign in and provides the
                    // code to use.
                    Console.WriteLine(info.Message);
                    return Task.FromResult(0);
                });
        }

It works and I can follow it through, but it is directing the user to the console, eg:

To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code RB2RUD56D to authenticate.

How can I get it to take them to the website instead for the user to proceed? The InitializeGraphForUserAuth function is:

        public static void InitializeGraphForUserAuth(Settings settings,
            Func<DeviceCodeInfo, CancellationToken, Task> deviceCodePrompt)
        {
            _settings = settings;

            var options = new DeviceCodeCredentialOptions
            {
                ClientId = settings.ClientId,
                TenantId = settings.TenantId,
                DeviceCodeCallback = deviceCodePrompt,
            };

            _deviceCodeCredential = new DeviceCodeCredential(options);

            _userClient = new GraphServiceClient(_deviceCodeCredential, settings.GraphUserScopes);
        }

I have also asked this question on StackOverflow.

In summary:

  1. How do I change this code to redirect the user to complete authentication using a browser rather than the console?
  2. How do we persist the access token so the user does not have to constantly authenticate?
  3. Finally, how does one sign out on demand programmatically?

Thank you!

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
13,495 questions
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.