forked from microsoftgraph/dotnetcore-console-sample
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
84 lines (71 loc) · 2.89 KB
/
Program.cs
File metadata and controls
84 lines (71 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
using Azure.Identity;
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Graph;
using Microsoft.Extensions.Configuration;
namespace ConsoleGraphTest
{
class Program
{
private static GraphServiceClient _graphServiceClient;
static void Main(string[] args)
{
// Load appsettings.json
var config = LoadAppSettings();
if (null == config)
{
Console.WriteLine("Missing or invalid appsettings.json file. Please see README.md for configuration instructions.");
return;
}
//Query using Graph SDK (preferred when possible)
GraphServiceClient graphClient = GetAuthenticatedGraphClient(config);
var requestOptions = new [] {new QueryOption("$top", "1")};
var graphResult = graphClient.Users.Request(requestOptions).GetAsync().Result;
Console.WriteLine("Graph SDK Result");
Console.WriteLine(graphResult[0].DisplayName);
}
private static GraphServiceClient GetAuthenticatedGraphClient(IConfigurationRoot config)
{
var tenantId = config["tenantId"];
var clientId = config["applicationId"];
var clientSecret = config["applicationSecret"];
//this specific scope means that application will default to what is defined in the application registration rather than using dynamic scopes
var scopes = new [] {"https://graph.microsoft.com/.default"};
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
Func<DeviceCodeInfo, CancellationToken, Task> callback = (code, cancellation) =>
{
Console.WriteLine(code.Message);
return Task.FromResult(0);
};
var deviceCodeCredential = new DeviceCodeCredential(callback, tenantId, clientId, options);
_graphServiceClient = new GraphServiceClient(deviceCodeCredential, scopes);
return _graphServiceClient;
}
private static IConfigurationRoot LoadAppSettings()
{
try
{
var config = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", false, true)
.Build();
// Validate required settings
if (string.IsNullOrEmpty(config["applicationId"]) ||
string.IsNullOrEmpty(config["redirectUri"]) ||
string.IsNullOrEmpty(config["tenantId"]))
{
return null;
}
return config;
}
catch (System.IO.FileNotFoundException)
{
return null;
}
}
}
}