Skip to content

Commit

Permalink
make cca creation not async
Browse files Browse the repository at this point in the history
  • Loading branch information
jennyf19 committed Mar 24, 2021
1 parent cbbae6c commit 1281902
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 32 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public AppServicesAuthenticationTokenAcquisition(
_tokenCacheProvider = tokenCacheProvider;
}

private async Task<IConfidentialClientApplication> GetOrCreateApplication()
private IConfidentialClientApplication GetOrCreateApplication()
{
if (_confidentialClientApplication == null)
{
Expand All @@ -81,8 +81,8 @@ private async Task<IConfidentialClientApplication> GetOrCreateApplication()
_confidentialClientApplication = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(options)
.WithHttpClientFactory(_httpClientFactory)
.Build();
await _tokenCacheProvider.InitializeAsync(_confidentialClientApplication.AppTokenCache).ConfigureAwait(false);
await _tokenCacheProvider.InitializeAsync(_confidentialClientApplication.UserTokenCache).ConfigureAwait(false);
_tokenCacheProvider.Initialize(_confidentialClientApplication.AppTokenCache);
_tokenCacheProvider.Initialize(_confidentialClientApplication.UserTokenCache);
}

return _confidentialClientApplication;
Expand All @@ -100,7 +100,7 @@ public async Task<string> GetAccessTokenForAppAsync(
throw new ArgumentNullException(nameof(scope));
}

var app = await GetOrCreateApplication().ConfigureAwait(false);
var app = GetOrCreateApplication();
AuthenticationResult result = await app.AcquireTokenForClient(new string[] { scope })
.ExecuteAsync()
.ConfigureAwait(false);
Expand Down Expand Up @@ -176,7 +176,7 @@ public async Task<AuthenticationResult> GetAuthenticationResultForUserAsync(
}

/// <inheritdoc/>
public async Task ReplyForbiddenWithWwwAuthenticateHeaderAsync(IEnumerable<string> scopes, MsalUiRequiredException msalServiceException, HttpResponse? httpResponse = null)
public Task ReplyForbiddenWithWwwAuthenticateHeaderAsync(IEnumerable<string> scopes, MsalUiRequiredException msalServiceException, HttpResponse? httpResponse = null)
{
// Not implemented for the moment
throw new NotImplementedException();
Expand All @@ -188,6 +188,5 @@ public Task<AuthenticationResult> GetAuthenticationResultForAppAsync(string scop
throw new NotImplementedException();
}
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously

}
}
30 changes: 14 additions & 16 deletions src/Microsoft.Identity.Web/TokenAcquisition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public async Task AddAccountToCacheFromAuthorizationCodeAsync(

try
{
_application = await GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);
_application = GetOrBuildConfidentialClientApplication();

// Do not share the access token with ASP.NET Core otherwise ASP.NET will cache it and will not send the OAuth 2.0 request in
// case a further call to AcquireTokenByAuthorizationCodeAsync in the future is required for incremental consent (getting a code requesting more scopes)
Expand Down Expand Up @@ -210,7 +210,7 @@ public async Task<AuthenticationResult> GetAuthenticationResultForUserAsync(

user = await GetAuthenticatedUserAsync(user).ConfigureAwait(false);

_application = await GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);
_application = GetOrBuildConfidentialClientApplication();

string authority = CreateAuthorityBasedOnTenantIfProvided(_application, tenantId);

Expand Down Expand Up @@ -263,7 +263,7 @@ public async Task<AuthenticationResult> GetAuthenticationResultForUserAsync(
/// for multi tenant apps or daemons.</param>
/// <param name="tokenAcquisitionOptions">Options passed-in to create the token acquisition object which calls into MSAL .NET.</param>
/// <returns>An authentication result for the app itself, based on its scopes.</returns>
public async Task<AuthenticationResult> GetAuthenticationResultForAppAsync(
public Task<AuthenticationResult> GetAuthenticationResultForAppAsync(
string scope,
string? tenant = null,
TokenAcquisitionOptions? tokenAcquisitionOptions = null)
Expand All @@ -289,10 +289,9 @@ public async Task<AuthenticationResult> GetAuthenticationResultForAppAsync(
}

// Use MSAL to get the right token to call the API
_application = await GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);
_application = GetOrBuildConfidentialClientApplication();
string authority = CreateAuthorityBasedOnTenantIfProvided(_application, tenant);

AuthenticationResult result;
var builder = _application
.AcquireTokenForClient(new string[] { scope }.Except(_scopesRequestedByMsal))
.WithSendX5C(_microsoftIdentityOptions.SendX5C)
Expand All @@ -310,9 +309,7 @@ public async Task<AuthenticationResult> GetAuthenticationResultForAppAsync(
}
}

result = await builder.ExecuteAsync()
.ConfigureAwait(false);
return result;
return builder.ExecuteAsync();
}

/// <summary>
Expand Down Expand Up @@ -384,7 +381,6 @@ await GetAuthenticationResultForUserAsync(
/// <param name="scopes">Scopes to consent to.</param>
/// <param name="msalServiceException">The <see cref="MsalUiRequiredException"/> that triggered the challenge.</param>
/// <param name="httpResponse">The <see cref="HttpResponse"/> to update.</param>
/// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
public async Task ReplyForbiddenWithWwwAuthenticateHeaderAsync(IEnumerable<string> scopes, MsalUiRequiredException msalServiceException, HttpResponse? httpResponse = null)
{
// A user interaction is required, but we are in a web API, and therefore, we need to report back to the client through a 'WWW-Authenticate' header https://tools.ietf.org/html/rfc6750#section-3.1
Expand All @@ -394,7 +390,7 @@ public async Task ReplyForbiddenWithWwwAuthenticateHeaderAsync(IEnumerable<strin
throw msalServiceException;
}

_application = await GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);
_application = GetOrBuildConfidentialClientApplication();

string consentUrl = $"{_application.Authority}/oauth2/v2.0/authorize?client_id={_applicationOptions.ClientId}"
+ $"&response_type=code&redirect_uri={_application.AppConfig.RedirectUri}"
Expand All @@ -421,6 +417,8 @@ public async Task ReplyForbiddenWithWwwAuthenticateHeaderAsync(IEnumerable<strin
httpResponse.StatusCode = (int)HttpStatusCode.Forbidden;

headers[HeaderNames.WWWAuthenticate] = new StringValues($"{Constants.Bearer} {parameterString}");

await Task.CompletedTask.ConfigureAwait(false); // we don't want to take a breaking change right now. will be for 2.0
}

/// <summary>
Expand All @@ -435,7 +433,7 @@ public async Task RemoveAccountAsync(RedirectContext context)
string? userId = user.GetMsalAccountId();
if (!string.IsNullOrEmpty(userId))
{
IConfidentialClientApplication app = await GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);
IConfidentialClientApplication app = GetOrBuildConfidentialClientApplication();

if (_microsoftIdentityOptions.IsB2C)
{
Expand All @@ -458,11 +456,11 @@ public async Task RemoveAccountAsync(RedirectContext context)
/// <summary>
/// Creates an MSAL confidential client application, if needed.
/// </summary>
internal /* for testing */ async Task<IConfidentialClientApplication> GetOrBuildConfidentialClientApplicationAsync()
internal /* for testing */ IConfidentialClientApplication GetOrBuildConfidentialClientApplication()
{
if (_application == null)
{
return await BuildConfidentialClientApplicationAsync().ConfigureAwait(false);
return BuildConfidentialClientApplication();
}

return _application;
Expand All @@ -471,7 +469,7 @@ public async Task RemoveAccountAsync(RedirectContext context)
/// <summary>
/// Creates an MSAL confidential client application.
/// </summary>
private async Task<IConfidentialClientApplication> BuildConfidentialClientApplicationAsync()
private IConfidentialClientApplication BuildConfidentialClientApplication()
{
var request = CurrentHttpContext?.Request;
string? currentUri = null;
Expand Down Expand Up @@ -535,8 +533,8 @@ private async Task<IConfidentialClientApplication> BuildConfidentialClientApplic
IConfidentialClientApplication app = builder.Build();
_application = app;
// Initialize token cache providers
await _tokenCacheProvider.InitializeAsync(app.AppTokenCache).ConfigureAwait(false);
await _tokenCacheProvider.InitializeAsync(app.UserTokenCache).ConfigureAwait(false);
_tokenCacheProvider.Initialize(app.AppTokenCache);
_tokenCacheProvider.Initialize(app.UserTokenCache);
return app;
}
catch (Exception ex)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ public interface IMsalTokenCacheProvider
/// Initializes a token cache (which can be a user token cache or an app token cache).
/// </summary>
/// <param name="tokenCache">Token cache for which to initialize the serialization.</param>
/// <returns>A <see cref="Task"/> that represents a completed initialization operation.</returns>
Task InitializeAsync(ITokenCache tokenCache);
void Initialize(ITokenCache tokenCache);

/// <summary>
/// Clear the user token cache.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ public abstract class MsalAbstractTokenCacheProvider : IMsalTokenCacheProvider
/// Initializes the token cache serialization.
/// </summary>
/// <param name="tokenCache">Token cache to serialize/deserialize.</param>
/// <returns>A <see cref="Task"/> that represents a completed initialization operation.</returns>
public Task InitializeAsync(ITokenCache tokenCache)
public void Initialize(ITokenCache tokenCache)
{
if (tokenCache == null)
{
Expand All @@ -28,8 +27,6 @@ public Task InitializeAsync(ITokenCache tokenCache)
tokenCache.SetBeforeAccessAsync(OnBeforeAccessAsync);
tokenCache.SetAfterAccessAsync(OnAfterAccessAsync);
tokenCache.SetBeforeWriteAsync(OnBeforeWriteAsync);

return Task.CompletedTask;
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public void VerifyCorrectAuthorityUsedInTokenAcquisitionTests(string tenant)
[InlineData(TestConstants.B2CLoginMicrosoft)]
[InlineData(TestConstants.B2CInstance, true)]
[InlineData(TestConstants.B2CLoginMicrosoft, true)]
public async Task VerifyCorrectAuthorityUsedInTokenAcquisition_B2CAuthorityTestsAsync(
public void VerifyCorrectAuthorityUsedInTokenAcquisition_B2CAuthorityTests(
string authorityInstance,
bool withTfp = false)
{
Expand All @@ -119,7 +119,7 @@ public async Task VerifyCorrectAuthorityUsedInTokenAcquisition_B2CAuthorityTests

InitializeTokenAcquisitionObjects();

IConfidentialClientApplication app = await _tokenAcquisition.GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);
IConfidentialClientApplication app = _tokenAcquisition.GetOrBuildConfidentialClientApplication();

string expectedAuthority = string.Format(
CultureInfo.InvariantCulture,
Expand All @@ -134,7 +134,7 @@ public async Task VerifyCorrectAuthorityUsedInTokenAcquisition_B2CAuthorityTests
[Theory]
[InlineData("https://localhost:1234")]
[InlineData("")]
public async Task VerifyCorrectRedirectUriAsync(
public void VerifyCorrectRedirectUriAsync(
string redirectUri)
{
_microsoftIdentityOptions = new MicrosoftIdentityOptions
Expand All @@ -149,7 +149,7 @@ public async Task VerifyCorrectRedirectUriAsync(

InitializeTokenAcquisitionObjects();

IConfidentialClientApplication app = await _tokenAcquisition.GetOrBuildConfidentialClientApplicationAsync().ConfigureAwait(false);
IConfidentialClientApplication app = _tokenAcquisition.GetOrBuildConfidentialClientApplication();

if (!string.IsNullOrEmpty(redirectUri))
{
Expand Down

0 comments on commit 1281902

Please sign in to comment.