From a858ddabd497b3aa1ecde7d13e4e3c106d44f637 Mon Sep 17 00:00:00 2001 From: Claire Novotny Date: Sat, 27 Feb 2021 09:23:05 -0500 Subject: [PATCH] Ensure auth context is reused across calls for caching --- src/SignClient/SignCommand.cs | 68 ++++++++++++++++++++--------------- 1 file changed, 39 insertions(+), 29 deletions(-) diff --git a/src/SignClient/SignCommand.cs b/src/SignClient/SignCommand.cs index 6783f916..196d54bc 100644 --- a/src/SignClient/SignCommand.cs +++ b/src/SignClient/SignCommand.cs @@ -121,41 +121,51 @@ CommandOption maxConcurrency var configuration = builder.Build(); - // Setup Refit - var settings = new RefitSettings + + Func> getAccessToken; + + + var authority = $"{configuration["SignClient:AzureAd:AADInstance"]}{configuration["SignClient:AzureAd:TenantId"]}"; + + var clientId = configuration["SignClient:AzureAd:ClientId"]; + var resourceId = configuration["SignClient:Service:ResourceId"]; + + // See if we have a Username option + if (username.HasValue()) { - AuthorizationHeaderValueGetter = async () => - { - var authority = $"{configuration["SignClient:AzureAd:AADInstance"]}{configuration["SignClient:AzureAd:TenantId"]}"; + // ROPC flow + var pca = PublicClientApplicationBuilder.Create(clientId) + .WithAuthority(authority) + .Build(); - var clientId = configuration["SignClient:AzureAd:ClientId"]; - var resourceId = configuration["SignClient:Service:ResourceId"]; + var secret = new NetworkCredential("", clientSecret.Value()).SecurePassword; - // See if we have a Username option - if (username.HasValue()) - { - // ROPC flow - var pca = PublicClientApplicationBuilder.Create(clientId) - .WithAuthority(authority) - .Build(); + getAccessToken = async () => + { + var tokenResult = await pca.AcquireTokenByUsernamePassword(new[] { $"{resourceId}/user_impersonation" }, username.Value(), secret).ExecuteAsync(); - var secret = new NetworkCredential("", clientSecret.Value()).SecurePassword; + return tokenResult.AccessToken; + }; + } + else + { + var context = ConfidentialClientApplicationBuilder.Create(clientId) + .WithAuthority(authority) + .WithClientSecret(clientSecret.Value()) + .Build(); - var tokenResult = await pca.AcquireTokenByUsernamePassword(new[] { $"{resourceId}/user_impersonation" }, username.Value(), secret).ExecuteAsync(); + getAccessToken = async () => + { + // Client credential flow + var res = await context.AcquireTokenForClient(new[] { $"{resourceId}/.default" }).ExecuteAsync(); + return res.AccessToken; + }; + } - return tokenResult.AccessToken; - } - else - { - var context = ConfidentialClientApplicationBuilder.Create(clientId) - .WithAuthority(authority) - .WithClientSecret(clientSecret.Value()) - .Build(); - // Client credential flow - var res = await context.AcquireTokenForClient(new[] { $"{resourceId}/.default" }).ExecuteAsync(); - return res.AccessToken; - } - } + // Setup Refit + var settings = new RefitSettings + { + AuthorizationHeaderValueGetter = getAccessToken };