Image-Sorter/Image Sorter/AuthenticationHelper.cs

103 lines
4.0 KiB
C#
Raw Normal View History

using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace Image_Sorter
{
public class AuthenticationHelper
{
// The Client ID is used by the application to uniquely identify itself to the v2.0 authentication endpoint.
static string clientId = Program.MsaClientId;
public static string[] Scopes = { "Files.Read.All" };
public static IPublicClientApplication app = PublicClientApplicationBuilder.Create(clientId).WithRedirectUri("http://localhost:8192/oauth2callback/").Build();
//public static PublicClientApplicationBuilder IdentityClientApp = PublicClientApplicationBuilder.Create(clientId);// new PublicClientApplication(clientId);
public static string AccessToken = null;
public static IAccount UserAccount = null;
public static DateTimeOffset Expiration;
private static GraphServiceClient graphClient = null;
// Get an access token for the given context and resourceId. An attempt is first made to
// acquire the token silently. If that fails, then we try to acquire the token by prompting the user.
public static GraphServiceClient GetAuthenticatedClient()
{
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-apibrowser-sample");
}));
return graphClient;
}
catch (Exception ex)
{
Console.WriteLine("Could not create a graph client: " + ex.Message);
}
}
return graphClient;
}
/// <summary>
/// Get Token for User.
/// </summary>
/// <returns>Token for user.</returns>
public static async Task<string> GetTokenForUserAsync()
{
AuthenticationResult authResult;
/*try
{
authResult = await app.AcquireTokenInteractive(null).WithPrompt(Microsoft.Identity.Client.Prompt.SelectAccount).ExecuteAsync();
AccessToken = authResult.AccessToken;
UserAccount = authResult.Account;
}
catch (Exception e)
{
//Console.WriteLine(e);
}*/
// Attempt to aquire an existing token. If we're already authed, the existing account will be valid
try
{
authResult = await app.AcquireTokenSilent(Scopes, UserAccount).ExecuteAsync();
AccessToken = authResult.AccessToken;
UserAccount = authResult.Account;
}
catch (Exception)
{
if (AccessToken == null || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5))
{
authResult = await app.AcquireTokenInteractive(null).WithPrompt(Microsoft.Identity.Client.Prompt.SelectAccount).ExecuteAsync();
AccessToken = authResult.AccessToken;
UserAccount = authResult.Account;
Expiration = authResult.ExpiresOn;
}
}
return AccessToken;
}
}
}