-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathGraphHelper.cs
More file actions
86 lines (71 loc) · 2.78 KB
/
GraphHelper.cs
File metadata and controls
86 lines (71 loc) · 2.78 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
85
86
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
using Azure.Core;
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
namespace GraphAppOnlyTutorial;
public class GraphHelper
{
// <AppOnlyAuthConfigSnippet>
// Settings object
private static Settings? settings;
// App-ony auth token credential
private static ClientSecretCredential? clientSecretCredential;
// Client configured with app-only authentication
private static GraphServiceClient? appClient;
public static void InitializeGraphForAppOnlyAuth(Settings settings)
{
GraphHelper.settings = settings;
// Ensure settings isn't null
_ = settings ??
throw new NullReferenceException("Settings cannot be null");
GraphHelper.settings = settings;
clientSecretCredential ??= new ClientSecretCredential(
GraphHelper.settings.TenantId, GraphHelper.settings.ClientId, GraphHelper.settings.ClientSecret);
appClient ??= new GraphServiceClient(
clientSecretCredential,
/* Use the default scope, which will request the scopes
configured on the app registration */
["https://graph.microsoft.com/.default"]);
}
// </AppOnlyAuthConfigSnippet>
// <GetAppOnlyTokenSnippet>
public static async Task<string> GetAppOnlyTokenAsync()
{
// Ensure credential isn't null
_ = clientSecretCredential ??
throw new NullReferenceException("Graph has not been initialized for app-only auth");
// Request token with given scopes
var context = new TokenRequestContext(["https://graph.microsoft.com/.default"]);
var response = await clientSecretCredential.GetTokenAsync(context);
return response.Token;
}
// </GetAppOnlyTokenSnippet>
// <GetUsersSnippet>
public static Task<UserCollectionResponse?> GetUsersAsync()
{
// Ensure client isn't null
_ = appClient ??
throw new NullReferenceException("Graph has not been initialized for app-only auth");
return appClient.Users.GetAsync((config) =>
{
/* Only request specific properties */
config.QueryParameters.Select = ["displayName", "id", "mail"];
/* Get at most 25 results */
config.QueryParameters.Top = 25;
/* Sort by display name */
config.QueryParameters.Orderby = ["displayName"];
});
}
// </GetUsersSnippet>
#pragma warning disable CS1998
// <MakeGraphCallSnippet>
/* This function serves as a playground for testing Graph snippets
or other code */
public static async Task MakeGraphCallAsync()
{
// INSERT YOUR CODE HERE
}
// </MakeGraphCallSnippet>
}