Skip to content

Commit 1112ad9

Browse files
authored
Merge pull request #152 from microsoft/release/update/210730070912
Sync up from Mainline branch for CommitId 25d429b36d15aab25cf647d6033…
2 parents cf69fe8 + a4b3a5b commit 1112ad9

File tree

7 files changed

+207
-171
lines changed

7 files changed

+207
-171
lines changed

src/GeneralTools/DataverseClient/Client/Auth/AuthProcessor.cs

Lines changed: 53 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ namespace Microsoft.PowerPlatform.Dataverse.Client.Auth
1717
internal class AuthProcessor
1818
{
1919
/// <summary>
20-
/// Executes Authentication against a service
20+
/// Executes Authentication against a service
2121
/// </summary>
2222
/// <param name="serviceUrl"></param>
2323
/// <param name="clientCredentials"></param>
@@ -35,38 +35,38 @@ internal class AuthProcessor
3535
/// <param name="addVersionInfoToUri">indicates if the serviceURI should be updated to include the /web?sdk version</param>
3636
/// <returns>AuthenticationResult containing a JWT Token for the requested Resource and user/app</returns>
3737
internal async static Task<ExecuteAuthenticationResults> ExecuteAuthenticateServiceProcessAsync(
38-
Uri serviceUrl,
39-
ClientCredentials clientCredentials,
40-
X509Certificate2 userCert,
41-
string clientId,
42-
Uri redirectUri,
43-
PromptBehavior promptBehavior,
44-
bool isOnPrem,
45-
string authority,
46-
object msalAuthClient ,
47-
DataverseTraceLogger logSink = null,
48-
bool useDefaultCreds = false,
49-
SecureString clientSecret = null,
38+
Uri serviceUrl,
39+
ClientCredentials clientCredentials,
40+
X509Certificate2 userCert,
41+
string clientId,
42+
Uri redirectUri,
43+
PromptBehavior promptBehavior,
44+
bool isOnPrem,
45+
string authority,
46+
object msalAuthClient ,
47+
DataverseTraceLogger logSink = null,
48+
bool useDefaultCreds = false,
49+
SecureString clientSecret = null,
5050
bool addVersionInfoToUri = true,
5151
IAccount user = null
5252
)
5353
{
5454
ExecuteAuthenticationResults processResult = new ExecuteAuthenticationResults();
5555
bool createdLogSource = false;
56-
56+
5757
AuthenticationResult authenticationResult = null;
5858

5959
try
6060
{
6161
if (logSink == null)
6262
{
63-
// when set, the log source is locally created.
63+
// when set, the log source is locally created.
6464
createdLogSource = true;
6565
logSink = new DataverseTraceLogger();
6666
}
6767

6868
string Authority = string.Empty;
69-
string Resource = string.Empty;
69+
string Resource = string.Empty;
7070

7171
bool clientCredentialsCheck = clientCredentials != null && clientCredentials.UserName != null && !string.IsNullOrEmpty(clientCredentials.UserName.UserName) && !string.IsNullOrEmpty(clientCredentials.UserName.Password);
7272
Resource = serviceUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
@@ -96,21 +96,21 @@ internal async static Task<ExecuteAuthenticationResults> ExecuteAuthenticateServ
9696
}
9797
// clientCredentialsCheck = false; // Forcing system to provide a UX popup vs UID/PW
9898

99-
// Assign outbound properties.
99+
// Assign outbound properties.
100100
processResult.Resource = Resource;
101-
processResult.Authority = Authority;
101+
processResult.Authority = Authority;
102102

103103
logSink.Log("AuthenticateService - found authority with name " + (string.IsNullOrEmpty(Authority) ? "<Not Provided>" : Authority));
104104
logSink.Log("AuthenticateService - found resource with name " + (string.IsNullOrEmpty(Resource) ? "<Not Provided>" : Resource));
105105

106106
Uri ResourceUri = new Uri(Resource);
107-
// Add Scope,
107+
// Add Scope,
108108
List<string> Scopes = Utilities.AddScope($"{Resource}/user_impersonation");
109109

110110
AuthenticationResult _authenticationResult = null;
111111
if (userCert != null || clientSecret != null)
112112
{
113-
// Add Scope,
113+
// Add Scope,
114114
Scopes.Clear();
115115
Scopes = Utilities.AddScope($"{Resource}.default" , Scopes);
116116

@@ -138,27 +138,27 @@ internal async static Task<ExecuteAuthenticationResults> ExecuteAuthenticateServ
138138
{
139139
logSink.Log("Initial ObtainAccessToken - CERT", TraceEventType.Verbose);
140140
cApp = cAppBuilder.WithCertificate(userCert).Build();
141-
_authenticationResult = await ObtainAccessTokenAsync(cApp, Scopes, logSink);
141+
_authenticationResult = await ObtainAccessTokenAsync(cApp, Scopes, logSink).ConfigureAwait(false);
142142
}
143143
else
144144
{
145145
if (clientSecret != null)
146146
{
147147
logSink.Log("Initial ObtainAccessToken - Client Secret", TraceEventType.Verbose);
148148
cApp = cAppBuilder.WithClientSecret(clientSecret.ToUnsecureString()).Build();
149-
_authenticationResult = await ObtainAccessTokenAsync(cApp, Scopes, logSink);
149+
_authenticationResult = await ObtainAccessTokenAsync(cApp, Scopes, logSink).ConfigureAwait(false);
150150
}
151151
else
152152
throw new Exception("Invalid Cert or Client Secret Auth flow");
153153
}
154154

155155
// Update the MSAL Client handed back.
156-
processResult.MsalAuthClient = cApp;
156+
processResult.MsalAuthClient = cApp;
157157
}
158158
else
159159
{
160160
PublicClientApplicationBuilder cApp = null;
161-
IPublicClientApplication pApp = null;
161+
IPublicClientApplication pApp = null;
162162
if (msalAuthClient is IPublicClientApplication)
163163
{
164164
pApp = (IPublicClientApplication)msalAuthClient;
@@ -179,8 +179,8 @@ internal async static Task<ExecuteAuthenticationResults> ExecuteAuthenticateServ
179179
pApp = cApp.Build();
180180
}
181181

182-
//Run user Auth flow.
183-
_authenticationResult = await ObtainAccessTokenAsync(pApp, Scopes, user, promptBehavior, clientCredentials, useDefaultCreds, logSink);
182+
//Run user Auth flow.
183+
_authenticationResult = await ObtainAccessTokenAsync(pApp, Scopes, user, promptBehavior, clientCredentials, useDefaultCreds, logSink).ConfigureAwait(false);
184184

185185
// Assign the application back out
186186
processResult.MsalAuthClient = pApp;
@@ -195,7 +195,7 @@ internal async static Task<ExecuteAuthenticationResults> ExecuteAuthenticateServ
195195
//_userId = _authenticationResult.Account;
196196
processResult.UserIdent = _authenticationResult.Account;
197197
}
198-
198+
199199
if (null == _authenticationResult)
200200
{
201201
throw new ArgumentNullException("AuthenticationResult");
@@ -207,7 +207,7 @@ internal async static Task<ExecuteAuthenticationResults> ExecuteAuthenticateServ
207207
{
208208
if (ex.InnerException is Microsoft.Identity.Client.MsalException)
209209
{
210-
var errorHandledResult = await ProcessAdalExecptionAsync(serviceUrl, clientCredentials, userCert, clientId, redirectUri, promptBehavior, isOnPrem, authority , msalAuthClient, logSink, useDefaultCreds , (Microsoft.Identity.Client.MsalException)ex.InnerException);
210+
var errorHandledResult = await ProcessAdalExecptionAsync(serviceUrl, clientCredentials, userCert, clientId, redirectUri, promptBehavior, isOnPrem, authority , msalAuthClient, logSink, useDefaultCreds , (Microsoft.Identity.Client.MsalException)ex.InnerException).ConfigureAwait(false);
211211
if (errorHandledResult != null)
212212
processResult = errorHandledResult;
213213
}
@@ -232,7 +232,7 @@ internal async static Task<ExecuteAuthenticationResults> ExecuteAuthenticateServ
232232
}
233233
finally
234234
{
235-
if (createdLogSource) // Only dispose it if it was created locally.
235+
if (createdLogSource) // Only dispose it if it was created locally.
236236
logSink.Dispose();
237237
}
238238
return processResult;
@@ -241,7 +241,7 @@ internal async static Task<ExecuteAuthenticationResults> ExecuteAuthenticateServ
241241

242242

243243
/// <summary>
244-
/// Token refresh flow for MSAL User Flows.
244+
/// Token refresh flow for MSAL User Flows.
245245
/// </summary>
246246
/// <param name="publicAppClient">MSAL Client to use.</param>
247247
/// <param name="scopes">Scopes to send in.</param>
@@ -260,10 +260,10 @@ internal async static Task<AuthenticationResult> ObtainAccessTokenAsync(
260260
bool useDefaultCreds = false,
261261
DataverseTraceLogger logSink = null)
262262
{
263-
// This works for user Auth flows.
263+
// This works for user Auth flows.
264264
AuthenticationResult _authenticationResult = null;
265265
bool clientCredentialsCheck = clientCredentials != null && clientCredentials.UserName != null && !string.IsNullOrEmpty(clientCredentials.UserName.UserName) && !string.IsNullOrEmpty(clientCredentials.UserName.Password);
266-
// Login user hint
266+
// Login user hint
267267
string loginUserHint = (clientCredentials != null && clientCredentials.UserName != null) ? clientCredentials.UserName.UserName : string.Empty;
268268
if (publicAppClient != null)
269269
{
@@ -284,11 +284,11 @@ internal async static Task<AuthenticationResult> ObtainAccessTokenAsync(
284284
{
285285
if (!string.IsNullOrEmpty(loginUserHint))
286286
{
287-
_authenticationResult = await publicAppClient.AcquireTokenByIntegratedWindowsAuth(scopes).WithUsername(loginUserHint).ExecuteAsync();
287+
_authenticationResult = await publicAppClient.AcquireTokenByIntegratedWindowsAuth(scopes).WithUsername(loginUserHint).ExecuteAsync().ConfigureAwait(false);
288288
}
289289
else
290290
{
291-
_authenticationResult = await publicAppClient.AcquireTokenByIntegratedWindowsAuth(scopes).ExecuteAsync();
291+
_authenticationResult = await publicAppClient.AcquireTokenByIntegratedWindowsAuth(scopes).ExecuteAsync().ConfigureAwait(false);
292292
}
293293
}
294294
else
@@ -315,32 +315,32 @@ internal async static Task<AuthenticationResult> ObtainAccessTokenAsync(
315315

316316
if (userPrompt != null)
317317
{
318-
_authenticationResult = await publicAppClient.AcquireTokenInteractive(scopes).WithLoginHint(loginUserHint).WithPrompt(userPrompt.Value).ExecuteAsync();
318+
_authenticationResult = await publicAppClient.AcquireTokenInteractive(scopes).WithLoginHint(loginUserHint).WithPrompt(userPrompt.Value).ExecuteAsync().ConfigureAwait(false);
319319
}
320320
else
321321
{
322322
if (account != null)
323323
{
324-
_authenticationResult = await publicAppClient.AcquireTokenSilent(scopes, account).ExecuteAsync();
324+
_authenticationResult = await publicAppClient.AcquireTokenSilent(scopes, account).ExecuteAsync().ConfigureAwait(false);
325325
}
326326
else
327327
{
328-
_authenticationResult = await publicAppClient.AcquireTokenInteractive(scopes).WithLoginHint(loginUserHint).ExecuteAsync();
328+
_authenticationResult = await publicAppClient.AcquireTokenInteractive(scopes).WithLoginHint(loginUserHint).ExecuteAsync().ConfigureAwait(false);
329329
}
330330
}
331331
}
332332
}
333333
}
334334
else
335335
{
336-
// throw here.
336+
// throw here.
337337
}
338338
return _authenticationResult;
339339
}
340340

341341

342342
/// <summary>
343-
/// Acquires Confidential client token.
343+
/// Acquires Confidential client token.
344344
/// </summary>
345345
/// <param name="confidentialAppClient">Confidential client application</param>
346346
/// <param name="scopes">Scope List</param>
@@ -351,15 +351,15 @@ internal async static Task<AuthenticationResult> ObtainAccessTokenAsync(
351351
List<string> scopes,
352352
DataverseTraceLogger logSink = null)
353353
{
354-
// This works for user Auth flows.
354+
// This works for user Auth flows.
355355
AuthenticationResult _authenticationResult = null;
356356
if (confidentialAppClient != null)
357357
{
358-
_authenticationResult = await confidentialAppClient.AcquireTokenForClient(scopes).ExecuteAsync();
358+
_authenticationResult = await confidentialAppClient.AcquireTokenForClient(scopes).ExecuteAsync().ConfigureAwait(false);
359359
}
360360
else
361361
{
362-
// throw here.
362+
// throw here.
363363
}
364364
return _authenticationResult;
365365
}
@@ -412,7 +412,7 @@ internal class AuthRoutingProperties
412412
}
413413

414414
/// <summary>
415-
/// Get authority and resource for this instance.
415+
/// Get authority and resource for this instance.
416416
/// </summary>
417417
/// <param name="targetServiceUrl">URI to query</param>
418418
/// <param name="logger">Logger to write info too</param>
@@ -423,12 +423,12 @@ private static async Task<AuthRoutingProperties> GetAuthorityFromTargetServiceAs
423423
AuthRoutingProperties authRoutingProperties = new AuthRoutingProperties();
424424
var client = clientFactory.CreateClient("DataverseHttpClientFactory");
425425
var rslt = await client.GetAsync(targetServiceUrl).ConfigureAwait(false);
426-
426+
427427
if ( rslt.StatusCode == System.Net.HttpStatusCode.NotFound || rslt.StatusCode == System.Net.HttpStatusCode.BadRequest )
428428
{
429-
// didnt find endpoint.
429+
// didnt find endpoint.
430430
logger.Log($"Failed to get Authority and Resource error. Attempt to Access Endpoint {targetServiceUrl.ToString()} resulted in {rslt.StatusCode}.", TraceEventType.Error);
431-
return authRoutingProperties;
431+
return authRoutingProperties;
432432
}
433433

434434
if (rslt.Headers.Contains("WWW-Authenticate"))
@@ -469,19 +469,19 @@ private static async Task<AuthRoutingProperties> GetAuthorityFromTargetServiceAs
469469
{
470470
string param;
471471
authenticateHeaderItems.TryGetValue(AuthorityKey, out param);
472-
authRoutingProperties.Authority =
472+
authRoutingProperties.Authority =
473473
param.Replace("oauth2/authorize", "") // swap out the old oAuth pattern.
474-
.Replace("common" , "organizations"); // swap common for organizations because MSAL reasons.
474+
.Replace("common" , "organizations"); // swap common for organizations because MSAL reasons.
475475
authenticateHeaderItems.TryGetValue(ResourceKey, out param);
476476
authRoutingProperties.Resource = param;
477477
}
478478
}
479479

480-
return authRoutingProperties;
480+
return authRoutingProperties;
481481
}
482482

483483
/// <summary>
484-
/// Process ADAL exception and provide common handlers.
484+
/// Process ADAL exception and provide common handlers.
485485
/// </summary>
486486
/// <param name="serviceUrl"></param>
487487
/// <param name="clientCredentials"></param>
@@ -499,18 +499,18 @@ private async static Task<ExecuteAuthenticationResults> ProcessAdalExecptionAsyn
499499
{
500500
if (adalEx.ErrorCode.Equals("interaction_required", StringComparison.OrdinalIgnoreCase) ||
501501
adalEx.ErrorCode.Equals("user_password_expired", StringComparison.OrdinalIgnoreCase) ||
502-
adalEx.ErrorCode.Equals("password_required_for_managed_user", StringComparison.OrdinalIgnoreCase) ||
502+
adalEx.ErrorCode.Equals("password_required_for_managed_user", StringComparison.OrdinalIgnoreCase) ||
503503
adalEx is Microsoft.Identity.Client.MsalUiRequiredException)
504504
{
505505
logSink.Log("ERROR REQUESTING TOKEN FROM THE AUTHENTICATION CONTEXT - USER intervention required", TraceEventType.Warning);
506506
// ADAL wants the User to do something,, determine if we are able to see a user
507507
if (promptBehavior == PromptBehavior.Always || promptBehavior == PromptBehavior.Auto)
508508
{
509509
// Switch to MFA user mode..
510-
Microsoft.Identity.Client.IAccount user = null; //TODO:UPDATE THIS OR REMOVE AS WE DETERMIN HOW TO SOLVE THIS ISSUE IN MSAL // new Microsoft.Identity.Client.AccountId();
510+
Microsoft.Identity.Client.IAccount user = null; //TODO:UPDATE THIS OR REMOVE AS WE DETERMIN HOW TO SOLVE THIS ISSUE IN MSAL // new Microsoft.Identity.Client.AccountId();
511511
user = null;
512512
//user = new UserIdentifier(clientCredentials.UserName.UserName, UserIdentifierType.OptionalDisplayableId);
513-
return await ExecuteAuthenticateServiceProcessAsync(serviceUrl, null, userCert, clientId, redirectUri, promptBehavior, isOnPrem, authority, msalAuthClient, logSink, useDefaultCreds: useDefaultCreds, user: user);
513+
return await ExecuteAuthenticateServiceProcessAsync(serviceUrl, null, userCert, clientId, redirectUri, promptBehavior, isOnPrem, authority, msalAuthClient, logSink, useDefaultCreds: useDefaultCreds, user: user).ConfigureAwait(false);
514514
}
515515
else
516516
{

0 commit comments

Comments
 (0)