-
Notifications
You must be signed in to change notification settings - Fork 1
/
MsalAuthenticationProvider.cs
47 lines (39 loc) · 1.26 KB
/
MsalAuthenticationProvider.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
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Graph;
namespace Helpers
{
public class MsalAuthenticationProvider : IAuthenticationProvider
{
private static MsalAuthenticationProvider _singleton;
private IConfidentialClientApplication _application;
private string[] _scopes;
private MsalAuthenticationProvider(IConfidentialClientApplication application, string[] scopes)
{
_application = application;
_scopes = scopes;
}
public static MsalAuthenticationProvider GetInstance(IConfidentialClientApplication application, string[] scopes)
{
if (_singleton == null)
{
_singleton = new MsalAuthenticationProvider(application, scopes);
}
return _singleton;
}
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
request.Headers.Authorization = new AuthenticationHeaderValue("bearer", await GetTokenAsync());
}
public async Task<string> GetTokenAsync()
{
AuthenticationResult result = null;
try {
result = await _application.AcquireTokenForClient(_scopes).ExecuteAsync();
} catch (MsalServiceException) { }
return result.AccessToken;
}
}
}