
Product
Announcing Bun and vlt Support in Socket
Bringing supply chain security to the next generation of JavaScript package managers
@equinor/fusion-framework-module-msal
Advanced tools
Microsoft Authentication Library (MSAL) integration module for Fusion Framework
@equinor/fusion-framework-module-msal provides secure Azure AD authentication for browser applications using Microsoft's MSAL (Microsoft Authentication Library). Perfect for web applications, SPAs, and React apps that need to authenticate with Microsoft services.
Version: This package now uses MSAL Browser v4, providing the latest security improvements and features from Microsoft.
pnpm add @equinor/fusion-framework-module-msal
import { enableMSAL, initialize, type IMsalProvider } from '@equinor/fusion-framework-module-msal';
import { ModulesConfigurator } from '@equinor/fusion-framework-module';
// 1. Configure the module
const configurator = new ModulesConfigurator();
enableMSAL(configurator, (builder) => {
builder.setClientConfig({
auth: {
clientId: 'your-client-id',
tenantId: 'your-tenant-id',
redirectUri: 'https://your-app.com/callback'
}
});
// With requiresAuth=true, the module will attempt automatic login during initialization
// and await a valid authenticated account before initialization completes
builder.setRequiresAuth(true);
});
// 2. Initialize the framework (auto-initializes auth provider)
const framework = await initialize(configurator);
const auth: IMsalProvider = framework.auth;
// 3. Optional: Handle authentication redirect manually (auto-called during initialization)
const redirectResult = await auth.handleRedirect();
if (redirectResult?.account) {
console.log('Authenticated:', redirectResult.account.username);
}
// 4. Use authentication
// Option A: Token acquisition (v4 format - recommended)
const token = await auth.acquireAccessToken({
request: { scopes: ['api://your-app-id/.default'] }
});
// Option B: Legacy format (still supported via v2 proxy)
const legacyToken = await auth.acquireAccessToken({
scopes: ['api://your-app-id/.default']
});
// Option C: Silent authentication with fallback
try {
const result = await auth.login({
request: { scopes: ['api://your-app-id/.default'] },
silent: true // Attempts SSO first
});
} catch {
// Fallback to interactive if silent fails
await auth.login({
request: { scopes: ['api://your-app-id/.default'] },
behavior: 'popup'
});
}
[!IMPORTANT] The
@equinor/fusion-framework-appenables this package by default, so applications using the app package do not need to enable this module manually.
| Setting | Description | Required |
|---|---|---|
auth.clientId | Azure AD application client ID | ✅ |
auth.tenantId | Azure AD tenant ID | ✅ |
auth.redirectUri | Authentication callback URL | Optional |
| Setting | Description | Default |
|---|---|---|
requiresAuth | Auto-authenticate on initialization | false |
version | Force specific MSAL version | Latest |
# Required
AZURE_CLIENT_ID=your-client-id
AZURE_TENANT_ID=your-tenant-id
# Optional
AZURE_REDIRECT_URI=https://your-app.com/callback
enableMSAL(configurator, configure?)Enables the MSAL module in your Fusion Framework application.
Parameters:
configurator: IModulesConfigurator - The modules configurator instanceconfigure?: (builder: { setClientConfig, setRequiresAuth }) => void - Optional configuration functionReturns: void
Example:
enableMSAL(configurator, (builder) => {
builder.setClientConfig({ auth: { clientId: '...', tenantId: '...' } });
builder.setRequiresAuth(true);
});
LoginOptionstype LoginOptions = {
request: PopupRequest | RedirectRequest; // MSAL request object
behavior?: 'popup' | 'redirect'; // Auth method (default: 'redirect')
silent?: boolean; // Attempt silent auth first (default: true)
};
LogoutOptionstype LogoutOptions = {
redirectUri?: string; // Redirect after logout
account?: AccountInfo; // Account to logout (defaults to active)
};
AcquireTokenOptionstype AcquireTokenOptions = {
request: PopupRequest | RedirectRequest; // MSAL request with scopes
behavior?: 'popup' | 'redirect'; // Auth method (default: 'redirect')
silent?: boolean; // Attempt silent first (default: true if account available)
};
IMsalProviderThe authentication provider interface available at framework.auth:
interface IMsalProvider {
// The MSAL PublicClientApplication instance
readonly client: IMsalClient;
// Current user account information
readonly account: AccountInfo | null;
// Initialize the MSAL provider
initialize(): Promise<void>;
// Acquire an access token for the specified scopes
acquireAccessToken(options: AcquireTokenOptionsLegacy): Promise<string | undefined>;
// Acquire full authentication result
acquireToken(options: AcquireTokenOptionsLegacy): Promise<AcquireTokenResult>;
// Login user interactively
login(options: LoginOptions): Promise<LoginResult>;
// Logout user (returns boolean)
logout(options?: LogoutOptions): Promise<boolean>;
// Handle authentication redirect (returns AuthenticationResult | null)
handleRedirect(): Promise<AuthenticationResult | null>;
}
// Note: defaultAccount and other deprecated v2 properties are available only
// when using a v2-compatible proxy via createProxyProvider()
The module implements a hoisting pattern where the authentication provider is created once at the root level and shared across all sub-modules. This ensures consistent authentication state throughout your application while maintaining security and performance.
[!IMPORTANT] Configure the auth module only in the root Fusion Framework instance - Sub-instances will automatically inherit the authentication configuration from the parent.
This package has been upgraded from MSAL Browser v2 to v4, providing the latest security improvements and features from Microsoft.
New MSAL Browser v4 Features:
Architecture Changes:
initialize() method must be called before using the providerAuto-initialization via Framework
// The provider initializes automatically when framework loads
const framework = await initialize(configurator);
const auth = framework.auth; // Already initialized
// Manual initialization is only needed for standalone usage
const provider = new MsalProvider(config);
await provider.initialize();
API Method Signature Updates
logout() now returns Promise<boolean> instead of Promise<void>handleRedirect() now returns Promise<AuthenticationResult | null> instead of Promise<void>Account Property Changes
account property (returns AccountInfo | null) - v4 nativedefaultAccount is deprecated and only available via v2 proxy layerdefaultAccount with account throughout your codeUpdate Token Acquisition (Recommended)
// Before (v2 format - still works via proxy)
const token = await framework.auth.acquireAccessToken({
scopes: ['api.read']
});
// After (v4 format - recommended)
const token = await framework.auth.acquireAccessToken({
request: { scopes: ['api.read'] }
});
Update Logout Handling
// Before
await framework.auth.logout();
// After (check return value)
const success = await framework.auth.logout();
if (success) {
// Handle successful logout
}
Update Redirect Handling
// Before
await framework.auth.handleRedirect();
// After (handle result)
const result = await framework.auth.handleRedirect();
if (result?.account) {
// User authenticated successfully
console.log('Logged in as:', result.account.username);
}
Update Configuration (if needed)
// Ensure only the root module configures MSAL
enableMSAL(configurator, (builder) => {
builder.setClientConfig({
auth: {
clientId: 'your-client-id',
tenantId: 'your-tenant-id',
redirectUri: 'https://your-app.com/callback'
}
});
builder.setRequiresAuth(true);
});
Remove Duplicate Configurations: Remove MSAL configuration from child modules
The module includes a v2 proxy layer that automatically converts v2 API calls to v4 format. This means:
{ scopes: [] } is still supporteddefaultAccount are available via v2 proxy (with deprecation warnings)| Issue | Solution |
|---|---|
| Authentication Loop | Ensure redirect URIs match your application's routing |
| Token Acquisition Fails | Check that required scopes are properly configured |
| Module Not Found | Ensure the module is properly configured and framework is initialized |
| Multiple MSAL Instances | Remove duplicate configurations from child modules |
| Redirect Returns Void | For redirect flows, use handleRedirect() after navigation completes |
| Token Empty/Undefined | Verify user is authenticated and scopes are correct |
The MSAL module includes built-in version checking to ensure compatibility between different MSAL library versions.
import { resolveVersion, VersionError } from '@equinor/fusion-framework-module-msal/versioning';
// Resolve and validate a version
const result = resolveVersion('2.0.0');
console.log(result.isLatest); // false
console.log(result.satisfiesLatest); // true
console.log(result.enumVersion); // MsalModuleVersion.V2
VersionError if requested major version is greater than latestVersionError with descriptive messageresolveVersion(version: string | SemVer): ResolvedVersionResolves and validates a version string against the latest available MSAL version.
Parameters:
version - Version string or SemVer object to resolveReturns: ResolvedVersion object containing:
wantedVersion: SemVer - The parsed requested versionlatestVersion: SemVer - The latest available versionisLatest: boolean - Whether the version is exactly the latestsatisfiesLatest: boolean - Whether the major version matches latestenumVersion: MsalModuleVersion - Corresponding enum versionThrows: VersionError for invalid or incompatible versions
VersionErrorError class for version-related issues with the following types:
InvalidVersion - Requested version is not a valid semverInvalidLatestVersion - Latest version parsing failed (build issue)MajorIncompatibility - Major version is greater than latestMinorMismatch - Minor version differs (warning only)PatchDifference - Patch version differs (info only)IncompatibleVersion - General incompatibilityimport { resolveVersion, VersionError } from '@equinor/fusion-framework-module-msal/versioning';
try {
const result = resolveVersion('3.0.0'); // Assuming latest is 2.x
} catch (error) {
if (error instanceof VersionError) {
console.error('Version error:', error.message);
console.error('Requested:', error.requestedVersion);
console.error('Latest:', error.latestVersion);
console.error('Type:', error.type);
}
}
FAQs
Microsoft Authentication Library (MSAL) integration module for Fusion Framework
The npm package @equinor/fusion-framework-module-msal receives a total of 1,741 weekly downloads. As such, @equinor/fusion-framework-module-msal popularity was classified as popular.
We found that @equinor/fusion-framework-module-msal demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Product
Bringing supply chain security to the next generation of JavaScript package managers

Product
A safer, faster way to eliminate vulnerabilities without updating dependencies

Product
Reachability analysis for Ruby is now in beta, helping teams identify which vulnerabilities are truly exploitable in their applications.