-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathAuthorityResolver.cs
More file actions
155 lines (136 loc) · 6.04 KB
/
AuthorityResolver.cs
File metadata and controls
155 lines (136 loc) · 6.04 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace Microsoft.PowerPlatform.Dataverse.Client.Auth
{
/// <summary>
/// Details of expected authentication.
/// </summary>
public sealed class AuthenticationDetails
{
/// <summary>
/// True if probing returned a WWW-Authenticate header.
/// </summary>
public bool Success { get; internal set; }
/// <summary>
/// Authority to initiate OAuth flow with.
/// </summary>
// TODO: the 2 Uris here should be nullable: Uri? but that requires to update C# used for this solution from current 7.x to C# 9 or 10
public Uri Authority { get; internal set; }
/// <summary>
/// OAuth resource to request authentication for.
/// </summary>
public Uri Resource { get; internal set; }
}
/// <summary>
/// Probes API endpoint to elicit a 401 response with the WWW-Authenticate header and processes the found information
/// </summary>
public sealed class AuthorityResolver
{
private const string AuthenticateHeader = "WWW-Authenticate";
private const string Bearer = "bearer";
private const string AuthorityKey = "authorization_uri";
private const string ResourceKey = "resource_id";
private readonly HttpClient _httpClient;
private readonly Action<TraceEventType, string> _logger;
/// <summary>
/// instantiate resolver, using specified HttpClient to be used.
/// </summary>
/// <param name="httpClient"></param>
/// <param name="logger"></param>
public AuthorityResolver(HttpClient httpClient, Action<TraceEventType, string> logger = null)
{
_ = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_httpClient = httpClient;
_logger = logger;
}
/// <summary>
/// Attemtps to solicit a WWW-Authenticate reply using an unauthenticated GET call to the given endpoint.
/// Parses returned header for details
/// </summary>
/// <param name="endpoint"></param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"></exception>
public async Task<AuthenticationDetails> ProbeForExpectedAuthentication(Uri endpoint)
{
_ = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
var details = new AuthenticationDetails();
HttpResponseMessage response;
try
{
response = await _httpClient.GetAsync(endpoint).ConfigureAwait(false);
}
catch (HttpRequestException ex)
{
var errDetails = string.Empty;
if (ex.InnerException is WebException wex)
{
errDetails = $"; details: {wex.Message} ({wex.Status})";
}
LogError($"Failed to get response from: {endpoint}; error: {ex.Message}{errDetails}");
return details;
}
if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.BadRequest)
{
// didn't find endpoint.
LogError($"Failed to get Authority and Resource error. Attempt to Access Endpoint {endpoint} resulted in {response.StatusCode}.");
return details;
}
if (response.Headers.Contains(AuthenticateHeader))
{
var authenticateHeader = response.Headers.GetValues(AuthenticateHeader).FirstOrDefault();
authenticateHeader = authenticateHeader.Trim();
// This also checks for cases like "BearerXXXX authorization_uri=...." and "Bearer" and "Bearer "
if (!authenticateHeader.StartsWith(Bearer, StringComparison.OrdinalIgnoreCase)
|| authenticateHeader.Length < Bearer.Length + 2
|| !char.IsWhiteSpace(authenticateHeader[Bearer.Length]))
{
LogError($"Malformed 'Bearer' format: {authenticateHeader}");
return details;
}
authenticateHeader = authenticateHeader.Substring(Bearer.Length).Trim();
IDictionary<string, string> authenticateHeaderItems = null;
try
{
authenticateHeaderItems =
EncodingHelper.ParseKeyValueListStrict(authenticateHeader, ',', false, true);
}
catch (ArgumentException)
{
LogError($"Malformed arguments in '{AuthenticateHeader}: {authenticateHeader}");
return details;
}
if (authenticateHeaderItems != null)
{
if (!authenticateHeaderItems.TryGetValue(AuthorityKey, out var auth))
{
LogError($"Response header from {endpoint} is missing expected key/value for {AuthorityKey}");
return details;
}
details.Authority = new Uri(
auth.Replace("oauth2/authorize", "") // swap out the old oAuth pattern.
.Replace("common", "organizations")); // swap common for organizations because MSAL reasons.
if (!authenticateHeaderItems.TryGetValue(ResourceKey, out var res))
{
LogError($"Response header from {endpoint} is missing expected key/value for {ResourceKey}");
return details;
}
details.Resource = new Uri(res);
details.Success = true;
}
}
return details;
}
private void LogError(string message)
{
if (_logger != null)
{
_logger(TraceEventType.Error, message);
}
}
}
}