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"; // Alternatively "[Enter your tenant, as obtained from the Azure portal, e.g. kko365.onmicrosoft.com]"
- private const string Authority = "https://login.microsoftonline.com/" + Tenant;
- // The MSAL Public client app
- private static IPublicClientApplication PublicClientApp;
- private static string MSGraphURL = "https://graph.microsoft.com/beta/";
- private static AuthenticationResult authResult;
- public static GraphServiceClient GetGraphClient()
- {
- if(graphClient == null)
- {
- // Create Microsoft Graph client.
- 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);
- // This header has been added to identify our sample in the Microsoft Graph service. If extracting this code for your project please remove.
- 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();
- // It's good practice to not do work on the UI thread, so use ConfigureAwait(false) whenever possible.
- IEnumerable
accounts = await PublicClientApp.GetAccountsAsync().ConfigureAwait(false); - IAccount firstAccount = accounts.FirstOrDefault();
- try
- {
- authResult = await PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
- .ExecuteAsync();
- }
- catch (MsalUiRequiredException ex)
- {
- // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
- 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!");
- }
Kiran MohantyPosted Mar 16, 2021, 12:12 PM
Gordana TasicPosted Mar 17, 2021, 10:32 AM
Mohsin AzamPosted Mar 17, 2021, 7:03 AM