Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public class RemoteAuthenticationService<
where TAccount : RemoteUserAccount
{
private static readonly TimeSpan _userCacheRefreshInterval = TimeSpan.FromSeconds(60);
private bool _initialized;
private Task? _initializeTask;
private readonly RemoteAuthenticationServiceJavaScriptLoggingOptions _loggingOptions;

// This defaults to 1/1/1970
Expand Down Expand Up @@ -208,10 +208,22 @@ protected internal virtual async ValueTask<ClaimsPrincipal> GetAuthenticatedUser
[DynamicDependency(JsonSerialized, typeof(RemoteAuthenticationServiceJavaScriptLoggingOptions))]
private async ValueTask EnsureAuthService()
{
if (!_initialized)
// Concurrent callers (for example the authentication state and an access token request
// during startup) share a single initialization rather than each calling into JS.
// A failed initialization is not cached, so the next caller retries it.
var initializeTask = _initializeTask ??= JsRuntime.InvokeVoidAsync("AuthenticationService.init", Options.ProviderOptions, _loggingOptions).AsTask();
try
{
await JsRuntime.InvokeVoidAsync("AuthenticationService.init", Options.ProviderOptions, _loggingOptions);
_initialized = true;
await initializeTask;
}
catch
{
if (ReferenceEquals(_initializeTask, initializeTask))
{
_initializeTask = null;
}

throw;
}
}
private async Task UpdateUserOnSuccess(RemoteAuthenticationResult<TRemoteAuthenticationState> result)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,58 @@ public async Task RemoteAuthenticationService_GetAccessToken_ComputesDefaultRetu
Assert.Equal(tokenOptions, (AccessTokenRequestOptions)testJsRuntime.PastInvocations[^1].args[0]);
}

[Fact]
public async Task RemoteAuthenticationService_ConcurrentCalls_InitializeJavaScriptServiceOnce()
{
// Arrange
var testJsRuntime = new TestJsRuntime { InitCompletion = new TaskCompletionSource() };
var options = CreateOptions();
var runtime = new RemoteAuthenticationService<RemoteAuthenticationState, RemoteUserAccount, OidcProviderOptions>(
testJsRuntime,
options,
new TestNavigationManager(),
new AccountClaimsPrincipalFactory<RemoteUserAccount>(Mock.Of<IAccessTokenProviderAccessor>()),
null);

testJsRuntime.GetUserResult = default;

// Act
var first = runtime.GetAuthenticatedUser().AsTask();
var second = runtime.GetAuthenticatedUser().AsTask();
testJsRuntime.InitCompletion.SetResult();
await Task.WhenAll(first, second);

// Assert
var invocations = testJsRuntime.PastInvocations.Select(i => i.identifier).ToArray();
Assert.Single(invocations, i => i == "AuthenticationService.init");
Assert.Equal(2, invocations.Count(i => i == "AuthenticationService.getUser"));
}

[Fact]
public async Task RemoteAuthenticationService_RetriesInitialization_AfterFailure()
{
// Arrange
var testJsRuntime = new TestJsRuntime { InitException = new JSException("init failed") };
var options = CreateOptions();
var runtime = new RemoteAuthenticationService<RemoteAuthenticationState, RemoteUserAccount, OidcProviderOptions>(
testJsRuntime,
options,
new TestNavigationManager(),
new AccountClaimsPrincipalFactory<RemoteUserAccount>(Mock.Of<IAccessTokenProviderAccessor>()),
null);

testJsRuntime.GetUserResult = default;

// Act
await Assert.ThrowsAsync<JSException>(() => runtime.GetAuthenticatedUser().AsTask());
await runtime.GetAuthenticatedUser();

// Assert
Assert.Equal(
new[] { "AuthenticationService.init", "AuthenticationService.init", "AuthenticationService.getUser" },
testJsRuntime.PastInvocations.Select(i => i.identifier).ToArray());
}

[Fact]
public async Task RemoteAuthenticationService_GetUser_ReturnsAnonymousClaimsPrincipal_ForUnauthenticatedUsers()
{
Expand Down Expand Up @@ -531,15 +583,40 @@ private class TestJsRuntime : IJSRuntime

public RemoteUserAccount GetUserResult { get; set; }

// When set, "AuthenticationService.init" doesn't complete until this does.
public TaskCompletionSource InitCompletion { get; set; }

// When set, the next "AuthenticationService.init" fails with this exception.
public Exception InitException { get; set; }

public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object[] args)
{
PastInvocations.Add((identifier, args));
return new ValueTask<TValue>((TValue)GetInvocationResult(identifier));
}
=> Invoke<TValue>(identifier, args);

public ValueTask<TValue> InvokeAsync<TValue>(string identifier, CancellationToken cancellationToken, object[] args)
=> Invoke<TValue>(identifier, args);

private ValueTask<TValue> Invoke<TValue>(string identifier, object[] args)
{
PastInvocations.Add((identifier, args));

if (identifier == "AuthenticationService.init")
{
if (InitException is { } exception)
{
InitException = null;
return ValueTask.FromException<TValue>(exception);
}

if (InitCompletion is { } completion)
{
return new ValueTask<TValue>(completion.Task.ContinueWith(
_ => (TValue)GetInvocationResult(identifier),
CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously,
TaskScheduler.Default));
}
}

return new ValueTask<TValue>((TValue)GetInvocationResult(identifier));
}

Expand Down
Loading