-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathAuthService.cs
76 lines (62 loc) · 2.55 KB
/
AuthService.cs
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Azure.Core;
using Azure.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Graph;
namespace MsGraphSamples.Services;
public interface IAuthService
{
GraphServiceClient GraphClient { get; }
void Logout();
}
public class AuthService : IAuthService
{
private readonly IConfiguration _configuration = new ConfigurationBuilder().AddUserSecrets<AuthService>().Build();
private readonly string _tokenPath;
private static readonly string[] _scopes = ["Directory.Read.All"];
private GraphServiceClient? _graphClient;
//public GraphServiceClient GraphClient => _graphClient ??= new GraphServiceClient(GetAppCredential());
public GraphServiceClient GraphClient => _graphClient ??= new GraphServiceClient(GetBrowserCredential());
public AuthService()
{
var localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
_tokenPath = Path.Combine(localAppData, AppDomain.CurrentDomain.FriendlyName, "authToken.bin");
}
private ClientSecretCredential GetAppCredential() => new(
_configuration["tenantId"],
_configuration["clientId"],
_configuration["clientSecret"]);
private InteractiveBrowserCredential GetBrowserCredential()
{
var credentialOptions = new InteractiveBrowserCredentialOptions
{
ClientId = _configuration["clientId"],
TokenCachePersistenceOptions = new TokenCachePersistenceOptions()
};
if (File.Exists(_tokenPath))
{
// use the cached token
using var authRecordStream = File.OpenRead(_tokenPath);
var authRecord = AuthenticationRecord.Deserialize(authRecordStream);
credentialOptions.AuthenticationRecord = authRecord;
return new InteractiveBrowserCredential(credentialOptions);
}
else
{
// create and cache the token
var browserCredential = new InteractiveBrowserCredential(credentialOptions);
var tokenRequestContext = new TokenRequestContext(_scopes);
var authRecord = browserCredential.Authenticate(tokenRequestContext);
Directory.CreateDirectory(Path.GetDirectoryName(_tokenPath)!);
using var authRecordStream = File.OpenWrite(_tokenPath);
authRecord.Serialize(authRecordStream);
return browserCredential;
}
}
public void Logout()
{
File.Delete(_tokenPath);
_graphClient = null;
}
}