-
Notifications
You must be signed in to change notification settings - Fork 1
/
ClientSecretAuthProvider.cs
51 lines (46 loc) · 1.62 KB
/
ClientSecretAuthProvider.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
using Microsoft.Graph;
using Microsoft.Identity.Client;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace GraphMessagesSample
{
public class ClientSecretAuthProvider : IAuthenticationProvider
{
private IConfidentialClientApplication msalClient;
private string appId;
private string clientSecret;
private string[] scopes;
private string tenantId;
public ClientSecretAuthProvider(string appId, string[] scopes, string tenantId, string clientSecret)
{
this.appId = appId;
this.clientSecret = clientSecret;
this.scopes = scopes;
this.tenantId = tenantId;
this.msalClient = ConfidentialClientApplicationBuilder.Create(this.appId)
.WithAuthority(AzureCloudInstance.AzurePublic, this.tenantId)
.WithClientSecret(this.clientSecret)
.Build();
}
public async Task<string> GetAuthorizationHeader()
{
try
{
var result = await this.msalClient
.AcquireTokenForClient(this.scopes)
.ExecuteAsync();
return result.CreateAuthorizationHeader();
}
catch (Exception exception)
{
Console.WriteLine($"Error getting access token: {exception.Message}");
return null;
}
}
public async Task AuthenticateRequestAsync(HttpRequestMessage requestMessage)
{
requestMessage.Headers.Add("Authorization", await GetAuthorizationHeader());
}
}
}