Created
April 10, 2019 07:41
-
-
Save chenxizhang/5051a486dcfbe9143450e2f0462ad150 to your computer and use it in GitHub Desktop.
Graph sample code for MSAL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Net.Http; | |
using System.Threading.Tasks; | |
using Microsoft.Graph; | |
using Microsoft.Identity.Client; | |
namespace testconsole | |
{ | |
class GraphAuthenticator : IAuthenticationProvider | |
{ | |
static string token; | |
static DateTimeOffset Expiration; | |
public async Task AuthenticateRequestAsync(HttpRequestMessage request) | |
{ | |
string[] scopes = { "user.read", "mail.read", "mail.send" }; | |
var app = PublicClientApplicationBuilder.Create("cfc3a225-ac57-45c9-aacd-969551f4825f").Build(); | |
AuthenticationResult result = null; | |
try | |
{ | |
result = await app.AcquireTokenInteractive(scopes, null).ExecuteAsync(); | |
token = result.AccessToken; | |
} | |
catch (Exception) | |
{ | |
if (string.IsNullOrEmpty(token) || Expiration <= DateTimeOffset.UtcNow.AddMinutes(5)) | |
{ | |
result = await app.AcquireTokenInteractive(scopes, null).ExecuteAsync(); | |
Expiration = result.ExpiresOn; | |
token = result.AccessToken; | |
} | |
} | |
request.Headers.Add("Authorization", $"Bearer {token}"); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var client = new GraphServiceClient(new GraphAuthenticator()); | |
Console.WriteLine(client.Me.Request().GetAsync().Result.DisplayName); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment