Skip to content
Merged
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
2 changes: 1 addition & 1 deletion src/Components/Web.JS/jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const ROOT_DIR = path.resolve(__dirname, '..', '..', '..');

module.exports = {
testEnvironment: 'node',
roots: ['<rootDir>/src','<rootDir>/test'],
roots: ['<rootDir>/src','<rootDir>/test','<rootDir>/../WebAssembly/Authentication.Msal/test'],
testMatch: ['**/*.test.ts'],
moduleFileExtensions: ['js', 'ts'],
transform: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -463,17 +463,21 @@ class MsalAuthorizeService implements AuthorizeService {
export class AuthenticationService {

static _infrastructureKey = 'Microsoft.Authentication.WebAssembly.Msal';
static _initialized: boolean;
private static _initialization: Promise<void> | undefined;
static instance: MsalAuthorizeService;

public static async init(settings: AuthorizeServiceConfiguration, jsLoggingOptions: JavaScriptLoggingOptions) {
if (!AuthenticationService._initialized) {
AuthenticationService.instance = new MsalAuthorizeService(settings, new Logger(jsLoggingOptions));
await AuthenticationService.instance.initialize();
AuthenticationService.instance.initializeMsalHandler();
AuthenticationService._initialized = true;
if (!AuthenticationService._initialization) {
const instance = new MsalAuthorizeService(settings, new Logger(jsLoggingOptions));
AuthenticationService.instance = instance;
AuthenticationService._initialization = instance.initialize()
.then(() => instance.initializeMsalHandler())
.catch(error => {
AuthenticationService._initialization = undefined;
throw error;
});
}
return Promise.resolve();
return AuthenticationService._initialization;
}

public static getUser() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

import { afterEach, beforeEach, describe, expect, jest, test } from '@jest/globals';
import type { PublicClientApplication } from '@azure/msal-browser';

describe('MSAL AuthenticationService initialization', () => {
const callbackUrl = 'http://localhost/authentication/login-callback';
const loggingOptions = { debugEnabled: false, traceEnabled: false };
let AuthenticationService: typeof import('../src/Interop/AuthenticationService').AuthenticationService;
let clients: ReturnType<typeof createMsalClient>[];
let pending: Promise<unknown>[];

beforeEach(async () => {
// Reload the real wrapper so each test starts with a fresh singleton.
jest.resetModules();
clients = [];
pending = [];
const msal = jest.requireActual<typeof import('@azure/msal-browser')>('@azure/msal-browser');
jest.doMock('@azure/msal-browser', () => ({
...msal,
PublicClientApplication: jest.fn(() => {
const client = createMsalClient(msal);
clients.push(client);
return client;
}),
}));
({ AuthenticationService } = await import('../src/Interop/AuthenticationService'));
});

afterEach(async () => {
for (const client of clients) {
client.finishInitialization();
}
await Promise.allSettled(pending);
});

test('nonoverlapping init calls initialize MSAL and handle the redirect only once', async () => {
const initialization = initialize();
expect(clients[0].handleRedirectPromise).not.toHaveBeenCalled();

clients[0].finishInitialization();
expect(await initialization).toEqual({ status: 'operationCompleted' });
expect(await initialize()).toEqual({ status: 'operationCompleted' });

expect(clients).toHaveLength(1);
expect(clients[0].initialize).toHaveBeenCalledTimes(1);
expect(clients[0].handleRedirectPromise).toHaveBeenCalledTimes(1);
});

test('overlapping init calls complete sign-in without handling a redirect on an uninitialized MSAL client', async () => {
const first = initialize();
const second = initialize();

// Complete the first caller while any competing client is still blocked.
clients[0].finishInitialization();
expect(await first).toEqual({ status: 'operationCompleted' });

for (const client of clients) {
client.finishInitialization();
}
expect(await second).toEqual({ status: 'operationCompleted' });
expect(clients).toHaveLength(1);
expect(clients[0].initialize).toHaveBeenCalledTimes(1);
expect(clients[0].handleRedirectPromise).toHaveBeenCalledTimes(1);
});

test('failed initialization rejects overlapping callers and can be retried', async () => {
const results = Promise.allSettled([initialize(), initialize()]);
const error = new Error('MSAL initialization failed');

expect(clients).toHaveLength(1);
clients[0].failInitialization(error);
expect(await results).toEqual([{ status: 'rejected', reason: error }, { status: 'rejected', reason: error }]);
expect(clients[0].handleRedirectPromise).not.toHaveBeenCalled();

const retry = initialize();
expect(clients).toHaveLength(2);
clients[1].finishInitialization();
expect(await retry).toEqual({ status: 'operationCompleted' });
expect(clients[1].initialize).toHaveBeenCalledTimes(1);
expect(clients[1].handleRedirectPromise).toHaveBeenCalledTimes(1);
});

function initialize() {
const result = AuthenticationService.init({
auth: {
clientId: 'test-client',
authority: 'https://login.microsoftonline.com/test-tenant',
redirectUri: callbackUrl,
knownAuthorities: [],
},
defaultAccessTokenScopes: [],
additionalScopesToConsent: [],
loginMode: 'redirect',
}, loggingOptions)
.then(() => AuthenticationService.completeSignIn(callbackUrl));
pending.push(result);
return result;
}
});

function createMsalClient(msal: typeof import('@azure/msal-browser')) {
let finishInitialization!: () => void;
let failInitialization!: (error: Error) => void;
const initialization = new Promise<void>((resolve, reject) => {
finishInitialization = resolve;
failInitialization = reject;
});
let initialized = false;

return {
finishInitialization,
failInitialization,
initialize: jest.fn<PublicClientApplication['initialize']>(() => initialization.then(() => {
initialized = true;
})),
handleRedirectPromise: jest.fn<PublicClientApplication['handleRedirectPromise']>(() => {
if (!initialized) {
return Promise.reject(new msal.BrowserAuthError(msal.BrowserAuthErrorCodes.uninitializedPublicClientApplication));
}

return Promise.resolve(null);
}),
};
}
13 changes: 13 additions & 0 deletions src/Components/test/E2ETest/Tests/RemoteAuthenticationTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,19 @@ public RemoteAuthenticationTest(
{
}

[Fact]
public void ConcurrentMsalInitialization_UsesSingleInitializedClient()
{
Navigate("/subdir/msal-initialization.html");

var result = Browser.Exists(By.Id("result"));
Browser.Equal("PASS", () => result.GetDomAttribute("data-status"));

Browser.Navigate().Refresh();
result = Browser.Exists(By.Id("result"));
Browser.Equal("PASS", () => result.GetDomAttribute("data-status"));
}

[Fact]
public void NavigateToLogin_PreservesExtraQueryParams()
{
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
<!-- Licensed to the .NET Foundation under one or more agreements.
The .NET Foundation licenses this file to you under the MIT license. -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Concurrent MSAL initialization</title>
</head>
<body>
<h1>Concurrent MSAL initialization</h1>
<pre id="result" data-status="running">Running...</pre>
<script src="_content/Microsoft.Authentication.WebAssembly.Msal/AuthenticationService.js"></script>
<script>
const settings = {
auth: {
clientId: "33333333-3333-3333-3333-333333333333",
authority: "https://login.microsoftonline.com/common",
redirectUri: location.origin + "/authentication/login-callback",
knownAuthorities: []
},
cache: { cacheLocation: "localStorage" },
loginMode: "popup",
defaultAccessTokenScopes: [],
additionalScopesToConsent: []
};
const loggingOptions = { debugEnabled: false, traceEnabled: false };

async function run() {
const first = AuthenticationService.init(structuredClone(settings), loggingOptions);
const firstClient = AuthenticationService.instance;
const second = AuthenticationService.init(structuredClone(settings), loggingOptions);
const sharedClient = firstClient === AuthenticationService.instance;
const results = await Promise.all([
first.then(() => AuthenticationService.completeSignIn(location.href)),
second.then(() => AuthenticationService.completeSignIn(location.href))
]);
const passed = sharedClient && results.every(result => result.status === "operationCompleted");
const output = document.getElementById("result");
output.dataset.status = passed ? "PASS" : "FAIL";
output.textContent = output.dataset.status + "\n" + JSON.stringify({ sharedClient, results }, null, 2);
}

run().catch(error => {
const output = document.getElementById("result");
output.dataset.status = "ERROR";
output.textContent = "ERROR\n" + String(error);
console.error(error);
});
</script>
</body>
</html>
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<ItemGroup>
<ProjectReference Include="$(RepoRoot)src\Components\WebAssembly\WebAssembly.Authentication\src\Microsoft.AspNetCore.Components.WebAssembly.Authentication.csproj" />
<ProjectReference Include="$(RepoRoot)src\Components\WebAssembly\WebAssembly\src\Microsoft.AspNetCore.Components.WebAssembly.csproj" />
<ProjectReference Include="$(RepoRoot)src\Components\WebAssembly\Authentication.Msal\src\Microsoft.Authentication.WebAssembly.Msal.csproj" />
</ItemGroup>

</Project>
Loading