I have two methods, the first one gets an access token to access AzureAD, the second is supposed to get user data. I'm able to get it to work when the code is all in the same method, but I'd like to eventually add command line arguments to call different methods, so I'm trying to have the authorization piece seperate and called whenever another method is called. Here's what I have so far.
using Microsoft.Identity.Client;
using System;
using System.Threading.Tasks;
using System.Configuration;
using System.Net.Http.Headers;
using PublicClientApplication = Microsoft.Identity.Client.PublicClientApplication;
namespace SharpZure
{
class SharpZure
{
static void Main(string[] args)
{
Auth().GetAwaiter().GetResult();
Console.ReadKey();
}
static async Task Auth()
{
var clientApp = PublicClientApplicationBuilder.Create(ConfigurationManager.AppSettings["clientId"]).Build();
string[] scopes = new string[] { "user.read" };
string token = null;
var app = PublicClientApplicationBuilder.Create(ConfigurationManager.AppSettings["clientId"]).Build();
var accounts = await app.GetAccountsAsync();
AuthenticationResult result = await app.AcquireTokenInteractive(scopes)
.ExecuteAsync();
token = result.AccessToken;
GraphServiceClient graphClient = new GraphServiceClient(
"https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}));
}
static async Task UserData()
{
Console.WriteLine("Display user details");
var currentUser = await graphClient.Me.Request().GetAsync();
Console.WriteLine(currentUser.DisplayName);
}
}
}
Of course the problem with this is that in the UserData() method, graphClient
isn't ever defined, as it's in the Auth() method.