I’m developing a small Windows form app to test Graph API functions. I
have two functionalities in the application, user's log in and create a
team. I created a class that contains a function for creating a
GraphServiceClient. I call this function both when the users logs in and
when I create a team. The problem is that the user login window is
displayed both times, and I want that once the user logs in, to somehow
save that GraphServiceClient instance so that the user does not have to
double logs in. Here is the code:
- public static class GraphManager
- {
- public static GraphServiceClient graphClient;
-
- private static string[] scopes = new string[] { "user.read" };
- public static string TokenForUser = null;
- public static DateTimeOffset expiration;
-
- private const string ClientId = "599ed98d-4356-4a96-ad37-04391e9c48dc";
-
- private const string Tenant = "common";
- private const string Authority = "https://login.microsoftonline.com/" + Tenant;
-
-
- private static IPublicClientApplication PublicClientApp;
-
- private static string MSGraphURL = "https://graph.microsoft.com/beta/";
- private static AuthenticationResult authResult;
-
- public static GraphServiceClient GetGraphClient()
- {
- if(graphClient == null)
- {
-
- try
- {
- graphClient = new GraphServiceClient(
- "https://graph.microsoft.com/v1.0",
- new DelegateAuthenticationProvider(
- async (requestMessage) =>
- {
- var token = await GetTokenForUserAsync();
- requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
-
- requestMessage.Headers.Add("SampleID", "uwp-csharp-snippets-sample");
-
- }));
- return graphClient;
- }
-
- catch (Exception ex)
- {
- Debug.WriteLine("Could not create a graph client: " + ex.Message);
- }
- }
- return graphClient;
- }
-
- public static async Task<string> GetTokenForUserAsync()
- {
- if (TokenForUser == null || expiration <= DateTimeOffset.UtcNow.AddMinutes(5))
- {
- PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
- .WithAuthority(Authority)
- .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
- .WithLogging((level, message, containsPii) =>
- {
- Debug.WriteLine($"MSAL: {level} {message} ");
- }, LogLevel.Warning, enablePiiLogging: false, enableDefaultPlatformLogging: true)
- .Build();
-
-
- IEnumerable<IAccount> accounts = await PublicClientApp.GetAccountsAsync().ConfigureAwait(false);
- IAccount firstAccount = accounts.FirstOrDefault();
-
- try
- {
- authResult = await PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
- .ExecuteAsync();
- }
- catch (MsalUiRequiredException ex)
- {
-
- Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
-
- authResult = await PublicClientApp.AcquireTokenInteractive(scopes)
- .ExecuteAsync()
- .ConfigureAwait(false);
- }
-
- TokenForUser = authResult.AccessToken;
- }
-
- return TokenForUser;
- }
-
- }
-
- private async void button1_Click(object sender, EventArgs e)
- {
-
- GraphServiceClient graphClient = GraphManager.GetGraphClient();
- User graphUser = await graphClient.Me.Request().GetAsync();
- label2.Text = graphUser.DisplayName;
- }
-
- private async void button2_Click(object sender, EventArgs e)
- {
- GraphServiceClient graphClient = GraphManager.GetGraphClient();
-
- var team = new Team
- {
- DisplayName = "Test1Test2",
- Description = "My sample team's description.",
- AdditionalData = new Dictionary<string, object>()
- {
- {"[email protected]", "https://graph.microsoft.com/beta/teamsTemplates('educationClass')" }
- }
- };
-
- await graphClient.Teams.Request().AddAsync(team);
- MessageBox.Show("Successfully created team!");
- }