question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[Bug] Broker fails to init when using PublishSingleFile

See original GitHub issue

Logs and network traces Below

Which version of MSAL.NET are you using? Client 4.52.0, Broker 4.52.0

Platform .Net Core 7.0, win10-x64

What authentication flow has the issue?

  • Desktop / Mobile
    • Interactive
    • Integrated Windows Authentication
    • Username Password
    • Device code flow (browserless)
  • Web app
    • Authorization code
    • On-Behalf-Of
  • Daemon app
    • Service to Service calls

Other? Silent flow

Is this a new or existing app? Existing app

Repro Add PublishSingleFile to csproj

<PublishSingleFile>true</PublishSingleFile>
    public async Task<AuthenticationResult> GetAsync(string[] scopes)
    {
        var publicClient = await CreatePublicClient({someappId});
        var accounts = await publicClient.GetAccountsAsync();
        if (accounts.Any())
        {
            // Assume first account
            var account = accounts.First();
            var silentAuthResult = await publicClient
                .AcquireTokenSilent(scopes, account)
                .ExecuteAsync();
            return silentAuthResult;
        }
        return null;
    }

    private static readonly BrokerOptions BrokerOptions = new(OperatingSystems.Windows);

    private static async Task<IPublicClientApplication> CreatePublicClient(string clientId)
    {
        var publicClient = PublicClientApplicationBuilder
            .Create(clientId)
            .WithBroker(BrokerOptions)
            .WithAuthority(AadAuthorityAudience.AzureAdMultipleOrgs)
            .WithRedirectUri(redirectUri)
            .Build();

        // Configure Cross-Execution Token Cache
        var storageProperties = new StorageCreationPropertiesBuilder("msal_cache.txt", MsalCacheHelper.UserRootDirectory)
            .Build();
        var cacheHelper = await MsalCacheHelper
            .CreateAsync(storageProperties);
        cacheHelper
            .RegisterCache(publicClient.UserTokenCache);

        return publicClient;
    }

Expected behavior Code is able to acquire a token silently

Actual behavior

PS  C:\Users\{username}\source\repos\{project}\bin\Release\net7.0\win10-x64\publish> .\{appname}.exe
[MSAL Logger, Verbose] True MSAL 4.52.0.0 MSAL.NetCore .NET 7.0.3 Microsoft Windows 10.0.22621 [2023-04-11 18:40:18Z - bd02acc0-7f07-4fa3-ad43-5034d937259d] [Microsoft.Identity.Client.Extensions] Before access
Acquiring lock for token cache
[MSAL Logger, Verbose] True MSAL 4.52.0.0 MSAL.NetCore .NET 7.0.3 Microsoft Windows 10.0.22621 [2023-04-11 18:40:18Z - bd02acc0-7f07-4fa3-ad43-5034d937259d] [Microsoft.Identity.Client.Extensions] Before access, the store has changed
[MSAL Logger, Verbose] True MSAL 4.52.0.0 MSAL.NetCore .NET 7.0.3 Microsoft Windows 10.0.22621 [2023-04-11 18:40:18Z - bd02acc0-7f07-4fa3-ad43-5034d937259d] [Microsoft.Identity.Client.Extensions] Read '10930' bytes from storage
[MSAL Logger, Verbose] True MSAL 4.52.0.0 MSAL.NetCore .NET 7.0.3 Microsoft Windows 10.0.22621 [2023-04-11 18:40:18Z - bd02acc0-7f07-4fa3-ad43-5034d937259d] [Microsoft.Identity.Client.Extensions] Deserializing the store
[MSAL Logger, LogAlways] True MSAL 4.52.0.0 MSAL.NetCore .NET 7.0.3 Microsoft Windows 10.0.22621 [2023-04-11 18:40:18Z] [Internal cache] Clearing user token cache accessor.
[MSAL Logger, Verbose] True MSAL 4.52.0.0 MSAL.NetCore .NET 7.0.3 Microsoft Windows 10.0.22621 [2023-04-11 18:40:18Z - bd02acc0-7f07-4fa3-ad43-5034d937259d] [Microsoft.Identity.Client.Extensions] After access
[MSAL Logger, LogAlways] True MSAL 4.52.0.0 MSAL.NetCore .NET 7.0.3 Microsoft Windows 10.0.22621 [2023-04-11 18:40:18Z] [Internal cache] Total number of cache partitions found while getting refresh tokens: 1
[MsalAuthenticationResolver] MsalClientException: wam_runtime_init_failed: The type initializer for 'Microsoft.Identity.Client.NativeInterop.API' threw an exception. See https://aka.ms/msal-net-wam#troubleshooting
Unhandled exception. MSAL.NetCore.4.52.0.0.MsalClientException:
        ErrorCode: wam_runtime_init_failed
Microsoft.Identity.Client.MsalClientException: The type initializer for 'Microsoft.Identity.Client.NativeInterop.API' threw an exception. See https://aka.ms/msal-net-wam#troubleshooting
 ---> System.TypeInitializationException: The type initializer for 'Microsoft.Identity.Client.NativeInterop.API' threw an exception.
 ---> System.NotSupportedException: CodeBase is not supported on assemblies loaded from a single-file bundle.
   at System.Reflection.RuntimeAssembly.get_CodeBase()
   at Microsoft.Identity.Client.NativeInterop.Platform.GetExecutingAssemblyDirectory()
   at Microsoft.Identity.Client.NativeInterop.API.GetPackagePathAndSetEnvironmentVariables()
   at Microsoft.Identity.Client.NativeInterop.API..cctor()
   --- End of inner exception stack trace ---
   at Microsoft.Identity.Client.NativeInterop.Module.AddRef(String handleName)
   at Microsoft.Identity.Client.NativeInterop.Core..ctor()
   at Microsoft.Identity.Client.Platforms.Features.RuntimeBroker.RuntimeBroker.<>c.<.cctor>b__24_0()
   --- End of inner exception stack trace ---
   at Microsoft.Identity.Client.Platforms.Features.RuntimeBroker.RuntimeBroker.<>c.<.cctor>b__24_0()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode)
--- End of stack trace from previous location ---
   at System.LazyHelper.ThrowException()
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.get_Value()
   at Microsoft.Identity.Client.Platforms.Features.RuntimeBroker.RuntimeBroker..ctor(CoreUIParent uiParent, ApplicationConfiguration appConfig, ILoggerAdapter logger)
   at Microsoft.Identity.Client.Broker.BrokerExtension.<>c.<AddRuntimeSupportForWam>b__2_0(CoreUIParent uiParent, ApplicationConfiguration appConfig, ILoggerAdapter logger)
   at Microsoft.Identity.Client.PlatformsCommon.Shared.AbstractPlatformProxy.CreateBroker(ApplicationConfiguration, CoreUIParent)
   at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.FetchTokensFromBrokerAsync(String, CancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.GetTokenResponseAsync(CancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.ExecuteAsync(CancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken )
   at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.ExecuteAsync(AcquireTokenCommonParameters, AcquireTokenInteractiveParameters, CancellationToken)
   at {appname}.Identity.MsalAuthenticationResolver.GetAsync(String[]) in  C:\Users\{username}\source\repos\{project}\Identity\MsalAuthenticationResolver.cs:line 57
   at {appname}.Program.Main(String[]) in  C:\Users\{username}\source\repos\{project}\Program.cs:line 21
   at {appname}.Program.<Main>(String[])
Inner Exception: System.TypeInitializationException: The type initializer for 'Microsoft.Identity.Client.NativeInterop.API' threw an exception.
 ---> System.NotSupportedException: CodeBase is not supported on assemblies loaded from a single-file bundle.
   at System.Reflection.RuntimeAssembly.get_CodeBase()
   at Microsoft.Identity.Client.NativeInterop.Platform.GetExecutingAssemblyDirectory()
   at Microsoft.Identity.Client.NativeInterop.API.GetPackagePathAndSetEnvironmentVariables()
   at Microsoft.Identity.Client.NativeInterop.API..cctor()
   --- End of inner exception stack trace ---
   at Microsoft.Identity.Client.NativeInterop.Module.AddRef(String handleName)
   at Microsoft.Identity.Client.NativeInterop.Core..ctor()
   at Microsoft.Identity.Client.Platforms.Features.RuntimeBroker.RuntimeBroker.<>c.<.cctor>b__24_0()

Possible solution

Additional context / logs / screenshots / links to code

Add any other context about the problem here, such as logs and screenshots, and even links to code.

Issue Analytics

  • State:closed
  • Created 5 months ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

3reactions
zachcwillsoncommented, Apr 11, 2023

Adding <IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract> to my csproj fixed the issue 😃

2reactions
trwalkecommented, Apr 11, 2023

@zachcwillson Have you tried <IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract> as a workaround?

Read more comments on GitHub >

github_iconTop Results From Across the Web

net5.0 'publish single file' makes LoadUnmanagedLibrary ...
The problem is that Assembly.Location is no longer usable in the case of single file publish. If you build using it with single...
Read more >
Single File publish doesn't work with a WPF app
The app doesn't run. There's no error, it just doesn't start. When I deploy the app without the "single file" option, the app...
Read more >
Cannot debug Avalonia project : RIDER-85851 - YouTrack
I thinl it because of PublishSingleFile when I remove this option, it works. Test Project file: MyApp.zip. Version: 2022.3 EAP 9. Build: ...
Read more >
Self-Contained Single-File does not produce a single file
I have a small .Net 5 console application with no dependencies on third party components. I have set it up to publish as...
Read more >
Cannot create iOS archive via Visual Studio / Pair-to-Mac ...
I can pair with the Mac without issue. When attempting to create an archive I get one error message 'Unable to connect Mac...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found