Skip to content

Commit

Permalink
Ensure auth context is reused across calls for caching
Browse files Browse the repository at this point in the history
  • Loading branch information
clairernovotny committed Feb 27, 2021
1 parent cb72bd0 commit a858dda
Showing 1 changed file with 39 additions and 29 deletions.
68 changes: 39 additions & 29 deletions src/SignClient/SignCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -121,41 +121,51 @@ CommandOption maxConcurrency

var configuration = builder.Build();

// Setup Refit
var settings = new RefitSettings

Func<Task<string>> 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
};


Expand Down

0 comments on commit a858dda

Please sign in to comment.