Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cjvandyk/412cfbcd9a7831b8ee14e6821ff848d9 to your computer and use it in GitHub Desktop.
Save cjvandyk/412cfbcd9a7831b8ee14e6821ff848d9 to your computer and use it in GitHub Desktop.
ModernAuth with MSAL Device Authentication Flow
using Microsoft.Identity.Client;
using System;
using System.Net.Http;
using System.Threading.Tasks;
public static async Task<string> GetAccessTokenAsync(string clientId, string tenantId)
{
var app = PublicClientApplicationBuilder.Create(clientId)
.WithAuthority($"https://login.microsoftonline.com/{tenantId}")
.Build();
var result = await app.AcquireTokenWithDeviceCode(new[] { "https://graph.microsoft.com/.default" },
callback => {
Console.WriteLine(callback.Message);
return Task.FromResult(0);
}).ExecuteAsync();
return result.AccessToken;
}
public static async Task<HttpResponseMessage> CallGraphApiAsync(string accessToken)
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
var response = await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me");
return response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment