-
Notifications
You must be signed in to change notification settings - Fork 403
Expand file tree
/
Copy pathBaseAbstractApplicationBuilder.cs
More file actions
363 lines (328 loc) · 16.7 KB
/
BaseAbstractApplicationBuilder.cs
File metadata and controls
363 lines (328 loc) · 16.7 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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using Microsoft.Identity.Client.Http;
using Microsoft.Identity.Client.Instance;
using Microsoft.Identity.Client.Instance.Discovery;
using Microsoft.Identity.Client.PlatformsCommon.Interfaces;
using Microsoft.Identity.Client.Utils;
using Microsoft.IdentityModel.Abstractions;
using Microsoft.Identity.Client.Internal;
using Microsoft.Identity.Client.Http.Retry;
using Microsoft.Identity.Client.ManagedIdentity.V2;
using System.Text.Json;
namespace Microsoft.Identity.Client
{
/// <summary>
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class BaseAbstractApplicationBuilder<T>
where T : BaseAbstractApplicationBuilder<T>
{
internal BaseAbstractApplicationBuilder(ApplicationConfiguration configuration)
{
Config = configuration;
// Ensure the default retry policy factory is set if the test factory was not provided
if (Config.RetryPolicyFactory == null)
{
Config.RetryPolicyFactory = new RetryPolicyFactory();
}
// Ensure the default csr factory is set if the test factory was not provided
if (Config.CsrFactory == null)
{
Config.CsrFactory = new DefaultCsrFactory();
}
}
internal ApplicationConfiguration Config { get; }
/// <summary>
/// Uses a specific <see cref="IMsalHttpClientFactory"/> to communicate
/// with the IdP. This enables advanced scenarios such as setting a proxy,
/// or setting the Agent.
/// </summary>
/// <param name="httpClientFactory">HTTP client factory</param>
/// <remarks>MSAL does not guarantee that it will not modify the HttpClient, for example by adding new headers.
/// Prior to the changes needed in order to make MSAL's httpClients thread safe (https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/pull/2046/files),
/// the httpClient had the possibility of throwing an exception stating "Properties can only be modified before sending the first request".
/// MSAL's httpClient will no longer throw this exception after 4.19.0 (https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/releases/tag/4.19.0)
/// see (https://aka.ms/msal-httpclient-info) for more information.
/// </remarks>
/// <returns>The builder to chain the .With methods</returns>
public T WithHttpClientFactory(IMsalHttpClientFactory httpClientFactory)
{
Config.HttpClientFactory = httpClientFactory;
return (T)this;
}
/// <summary>
/// Uses a specific <see cref="IMsalHttpClientFactory"/> to communicate
/// with the IdP. This enables advanced scenarios such as setting a proxy,
/// or setting the Agent.
/// </summary>
/// <param name="httpClientFactory">HTTP client factory</param>
/// <param name="retryOnceOn5xx">Configures MSAL to retry on 5xx server errors. When enabled (on by default), MSAL will wait 1 second after receiving
/// a 5xx error and then retry the http request again.
/// When disabled, the developer will be responsible for configuring their own retry policy in their custom IMsalHttpClientFactory.</param>
/// <remarks>MSAL does not guarantee that it will not modify the HttpClient, for example by adding new headers.
/// Prior to the changes needed in order to make MSAL's httpClients thread safe (https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/pull/2046/files),
/// the httpClient had the possibility of throwing an exception stating "Properties can only be modified before sending the first request".
/// MSAL's httpClient will no longer throw this exception after 4.19.0 (https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/releases/tag/4.19.0)
/// see (https://aka.ms/msal-httpclient-info) for more information.
/// If you only want to configure the retryOnceOn5xx parameter, set httpClientFactory to null and MSAL will use the default http client.
/// </remarks>
/// <returns>The builder to chain the .With methods</returns>
public T WithHttpClientFactory(IMsalHttpClientFactory httpClientFactory, bool retryOnceOn5xx)
{
Config.HttpClientFactory = httpClientFactory;
Config.DisableInternalRetries = !retryOnceOn5xx;
return (T)this;
}
internal T WithHttpManager(IHttpManager httpManager)
{
Config.HttpManager = httpManager;
return (T)this;
}
/// <summary>
/// Sets the logging callback. For details see https://aka.ms/msal-net-logging
/// </summary>
/// <param name="loggingCallback"></param>
/// <param name="logLevel">Desired level of logging. The default is LogLevel.Info</param>
/// <param name="enablePiiLogging">Boolean used to enable/disable logging of
/// Personally Identifiable Information (PII).
/// PII logs are never written to default outputs like Console, Logcat or NSLog
/// Default is set to <c>false</c>, which ensures that your application is compliant with GDPR.
/// You can set it to <c>true</c> for advanced debugging requiring PII
/// If both WithLogging apis are set, the other one will override the this one
/// </param>
/// <param name="enableDefaultPlatformLogging">Flag to enable/disable logging to platform defaults.
/// In Desktop, Event Tracing is used. In iOS, NSLog is used.
/// In android, Logcat is used. The default value is <c>false</c>
/// </param>
/// <returns>The builder to chain the .With methods</returns>
/// <exception cref="InvalidOperationException"/> is thrown if the loggingCallback
/// was already set on the application builder
public T WithLogging(
LogCallback loggingCallback,
LogLevel? logLevel = null,
bool? enablePiiLogging = null,
bool? enableDefaultPlatformLogging = null)
{
if (Config.LoggingCallback != null)
{
throw new InvalidOperationException(MsalErrorMessage.LoggingCallbackAlreadySet);
}
Config.LoggingCallback = loggingCallback;
Config.LogLevel = logLevel ?? Config.LogLevel;
Config.EnablePiiLogging = enablePiiLogging ?? Config.EnablePiiLogging;
Config.IsDefaultPlatformLoggingEnabled = enableDefaultPlatformLogging ?? Config.IsDefaultPlatformLoggingEnabled;
return (T)this;
}
/// <summary>
/// Sets the Identity Logger. For details see https://aka.ms/msal-net-logging
/// </summary>
/// <param name="identityLogger">IdentityLogger</param>
/// <param name="enablePiiLogging">Boolean used to enable/disable logging of
/// Personally Identifiable Information (PII).
/// PII logs are never written to default outputs like Console, Logcat or NSLog
/// Default is set to <c>false</c>, which ensures that your application is compliant with GDPR.
/// You can set it to <c>true</c> for advanced debugging requiring PII
/// If both WithLogging apis are set, this one will override the other
/// </param>
/// <returns>The builder to chain the .With methods</returns>
public T WithLogging(
IIdentityLogger identityLogger,
bool enablePiiLogging = false)
{
Config.IdentityLogger = identityLogger;
Config.EnablePiiLogging = enablePiiLogging;
return (T)this;
}
/// <summary>
/// Sets the Debug logging callback to a default debug method which displays
/// the level of the message and the message itself. For details see https://aka.ms/msal-net-logging
/// </summary>
/// <param name="logLevel">Desired level of logging. The default is LogLevel.Info</param>
/// <param name="enablePiiLogging">Boolean used to enable/disable logging of
/// Personally Identifiable Information (PII).
/// PII logs are never written to default outputs like Console, Logcat or NSLog
/// Default is set to <c>false</c>, which ensures that your application is compliant with GDPR.
/// You can set it to <c>true</c> for advanced debugging requiring PII
/// </param>
/// <param name="withDefaultPlatformLoggingEnabled">Flag to enable/disable logging to platform defaults.
/// In Desktop, Event Tracing is used. In iOS, NSLog is used.
/// In android, logcat is used. The default value is <c>false</c>
/// </param>
/// <returns>The builder to chain the .With methods</returns>
/// <exception cref="InvalidOperationException"/> is thrown if the loggingCallback
/// was already set on the application builder by calling <see cref="WithLogging(LogCallback, LogLevel?, bool?, bool?)"/>
/// <seealso cref="WithLogging(LogCallback, LogLevel?, bool?, bool?)"/>
[EditorBrowsable(EditorBrowsableState.Never)]
public T WithDebugLoggingCallback(
LogLevel logLevel = LogLevel.Info,
bool enablePiiLogging = false,
bool withDefaultPlatformLoggingEnabled = false)
{
WithLogging(
(level, message, _) => { Debug.WriteLine($"{level}: {message}"); },
logLevel,
enablePiiLogging,
withDefaultPlatformLoggingEnabled);
return (T)this;
}
/// <summary>
/// Sets application options, which can, for instance have been read from configuration files.
/// See https://aka.ms/msal-net-application-configuration.
/// </summary>
/// <param name="applicationOptions">Application options</param>
/// <returns>The builder to chain the .With methods</returns>
protected T WithOptions(BaseApplicationOptions applicationOptions)
{
WithLogging(
null,
applicationOptions.LogLevel,
applicationOptions.EnablePiiLogging,
applicationOptions.IsDefaultPlatformLoggingEnabled);
return (T)this;
}
/// <summary>
/// Allows usage of experimental features and APIs. If this flag is not set, experimental features
/// will throw an exception. For details see https://aka.ms/msal-net-experimental-features
/// </summary>
/// <remarks>
/// Changes in the public API of experimental features will not result in an increment of the major version of this library.
/// For these reason we advise against using these features in production.
/// </remarks>
public T WithExperimentalFeatures(bool enableExperimentalFeatures = true)
{
Config.ExperimentalFeaturesEnabled = enableExperimentalFeatures;
return (T)this;
}
/// <summary>
/// Sets the name of the calling SDK API for telemetry purposes.
/// </summary>
/// <param name="clientName">The name of the SDK API for telemetry purposes.</param>
/// <returns></returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public T WithClientName(string clientName)
{
Config.ClientName = GetValueIfNotEmpty(Config.ClientName, clientName);
return this as T;
}
/// <summary>
/// Sets the version of the calling SDK for telemetry purposes.
/// </summary>
/// <param name="clientVersion">The version of the calling SDK for telemetry purposes.</param>
/// <returns></returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public T WithClientVersion(string clientVersion)
{
Config.ClientVersion = GetValueIfNotEmpty(Config.ClientVersion, clientVersion);
return this as T;
}
/// <summary>
/// Internal only: Allows tests to inject a custom retry policy factory.
/// </summary>
/// <param name="factory">The retry policy factory to use.</param>
/// <returns>The builder for chaining.</returns>
internal T WithRetryPolicyFactory(IRetryPolicyFactory factory)
{
Config.RetryPolicyFactory = factory;
return (T)this;
}
/// <summary>
/// Internal only: Allows tests to inject a custom csr factory.
/// </summary>
/// <param name="factory">The csr factory to use.</param>
/// <returns>The builder for chaining.</returns>
internal T WithCsrFactory(ICsrFactory factory)
{
Config.CsrFactory = factory;
return (T)this;
}
internal virtual ApplicationConfiguration BuildConfiguration()
{
ResolveAuthority();
return Config;
}
internal void ResolveAuthority()
{
if (Config.Authority?.AuthorityInfo != null)
{
// Both WithAuthority and WithTenant were used at app config level
if (!string.IsNullOrEmpty(Config.TenantId))
{
string tenantedAuthority = Config.Authority.GetTenantedAuthority(
Config.TenantId,
forceSpecifiedTenant: true);
Config.Authority = Authority.CreateAuthority(
tenantedAuthority,
Config.Authority.AuthorityInfo.ValidateAuthority);
}
}
else
{
string authorityInstance = GetAuthorityInstance();
string authorityAudience = GetAuthorityAudience();
var authorityInfo = new AuthorityInfo(
AuthorityType.Aad,
new Uri($"{authorityInstance}/{authorityAudience}").ToString(),
Config.ValidateAuthority);
Config.Authority = new AadAuthority(authorityInfo);
}
}
private string GetAuthorityAudience()
{
if (!string.IsNullOrWhiteSpace(Config.TenantId) &&
Config.AadAuthorityAudience != AadAuthorityAudience.None &&
Config.AadAuthorityAudience != AadAuthorityAudience.AzureAdMyOrg)
{
// Conflict, user has specified a string tenantId and the enum audience value for AAD, which is also the tenant.
throw new InvalidOperationException(MsalErrorMessage.TenantIdAndAadAuthorityInstanceAreMutuallyExclusive);
}
if (Config.AadAuthorityAudience != AadAuthorityAudience.None)
{
return AuthorityInfo.GetAadAuthorityAudienceValue(Config.AadAuthorityAudience, Config.TenantId);
}
if (!string.IsNullOrWhiteSpace(Config.TenantId))
{
return Config.TenantId;
}
return AuthorityInfo.GetAadAuthorityAudienceValue(AadAuthorityAudience.AzureAdAndPersonalMicrosoftAccount, string.Empty);
}
private string GetAuthorityInstance()
{
// Check if there's enough information in the existing config to build up a default authority.
if (!string.IsNullOrWhiteSpace(Config.Instance) && Config.AzureCloudInstance != AzureCloudInstance.None)
{
// Conflict, user has specified a string instance and the enum instance value.
throw new InvalidOperationException(MsalErrorMessage.InstanceAndAzureCloudInstanceAreMutuallyExclusive);
}
if (!string.IsNullOrWhiteSpace(Config.Instance))
{
Config.Instance = Config.Instance.TrimEnd(' ', '/');
return Config.Instance;
}
if (Config.AzureCloudInstance != AzureCloudInstance.None)
{
return AuthorityInfo.GetCloudUrl(Config.AzureCloudInstance);
}
return AuthorityInfo.GetCloudUrl(AzureCloudInstance.AzurePublic);
}
internal void ValidateUseOfExperimentalFeature([System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
{
if (!Config.ExperimentalFeaturesEnabled)
{
throw new MsalClientException(
MsalError.ExperimentalFeature,
MsalErrorMessage.ExperimentalFeature(memberName));
}
}
internal static string GetValueIfNotEmpty(string original, string value)
{
return string.IsNullOrWhiteSpace(value) ? original : value;
}
}
}