-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAuthHelper.cs
More file actions
67 lines (52 loc) · 2.08 KB
/
AuthHelper.cs
File metadata and controls
67 lines (52 loc) · 2.08 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
using Newtonsoft.Json;
public class AuthHelper
{
/// <summary>
/// The header to use for OAuth authentication.
/// </summary>
public const string OAuthHeader = "Authorization";
private HttpClient client = new HttpClient();
public ClientConfiguration clientConfiguration { get; set; }
/// <summary>
/// Retrieves an authentication header from the service.
/// </summary>
/// <returns>The authentication header for the Web API call.</returns>
public async Task<string> getToken()
{
Dictionary<string, string> postData = new Dictionary<string, string>();
postData.Add("grant_type", "client_credentials");
postData.Add("client_id", clientConfiguration.ClientId);
postData.Add("client_secret", clientConfiguration.ClientSecret);
postData.Add("resource", clientConfiguration.Resource);
string url = $"https://login.microsoftonline.com/{clientConfiguration.TenantId}/oauth2/token";
string result = string.Empty;
try
{
string response = await PostHTTPRequestAsync(url, postData);
AuthResponse authresponse = JsonConvert.DeserializeObject<AuthResponse>(response);
result = authresponse.access_token;
}
catch (Exception ex)
{
//ConsoleList.(ex.Message);
}
return result;
}
private async Task<string> PostHTTPRequestAsync(string url, Dictionary<string, string> data)
{
HttpContent formContent = new FormUrlEncodedContent(data);
HttpResponseMessage response = await client.PostAsync(url, formContent).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
public class AuthResponse
{
public string token_type { get; set; }
public string expires_in { get; set; }
public string ext_expires_in { get; set; }
public string expires_on { get; set; }
public string not_before { get; set; }
public string resource { get; set; }
public string access_token { get; set; }
}