Skip to content

[Bug] SSL Connection refused when calling ASP.NET Core API endpoints from .NET MAUI App on Android #62966

Closed

Description

@tanvirarjel

The ASP.NET Core Web API app is up and running. Making requests to the API endpoints from Blazor Web Assembly works perfectly fine. Whenever making request from the .NET MAUI Blazor App it's throwing the following exception:

[DOTNET] System.Net.Http.HttpRequestException: Connection refused (localhost:44363)
[DOTNET]  ---> System.Net.Sockets.SocketException (111): Connection refused
[DOTNET]    at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken 
[DOTNET] cancellationToken) in System.Net.Sockets.dll:token 0x60002b9+0x1f
[DOTNET]    at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource.GetResult(Int16 token) in System.Net.Sockets.dll:token 0x60002b3+0x26
[DOTNET]    at Syst
[DOTNET] em.Net.Sockets.Socket.<ConnectAsync>g__WaitForConnectWithCancellation|277_0(AwaitableSocketAsyncEventArgs saea, ValueTask connectTask, CancellationToken cancellationToken) in System.Net.Sockets.dll:token 0x600029c+0xa4
[DOTNET]    at System.Net.Http.HttpConnectionP
[DOTNET] ool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x6000700+0x1b4
[DOTNET]    --- End of inner exception stack trace ---
[DOTNET]    at System.Net.Http.HttpC
[DOTNET] onnectionPool.ConnectToTcpHostAsync(String host, Int32 port, HttpRequestMessage initialRequest, Boolean async, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x6000700+0x298
[DOTNET]    at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpReque
[DOTNET] stMessage request, Boolean async, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x60006ff+0x14d
[DOTNET]    at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellati
[DOTNET] onToken) in System.Net.Http.dll:token 0x6000701+0x8f
[DOTNET]    at System.Net.Http.HttpConnectionPool.SendUsingHttp11Async(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x60006f1
[DOTNET] +0x15d
[DOTNET]    at System.Net.Http.HttpConnectionPool.DetermineVersionAndSendAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x60006f2+0x224
[DOTNET]    at System.Net.Http.HttpConne
[DOTNET] ctionPool.SendAndProcessAltSvcAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x60006f3+0x8e
[DOTNET] ssage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken) in System.Net.Http.dll:token 0x60006f4+0x99
[DOTNET]    at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequ07-16 12:39:49.024 I/DOTNET  (16085):    at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationT
[DOTNET] oken) in System.Net.Http.dll:token 0x6000787+0x94
[DOTNET]    at Microsoft.Extensions.Http.Logging.LoggingHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in Microsoft.Extensions.Http.dll:token 0x60000c3+0xd7
[DOTNET]    at MauiB
[DOTNET] lazor.Shared.Common.AuthorizationDelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in D:\GitHub\CleanArchitecture\src\ClientApps\MauiBlazor.Shared\Common\AuthorizationDelegatingHandler.cs:line 43
[DOTNET]    at Microsoft.E
[DOTNET] xtensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in Microsoft.Extensions.Http.dll:token 0x60000c8+0xef
[DOTNET] ge request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken) in System.Net.Http.dll:token 0x600022f+0x1b7
[DOTNET] lazor.Shared.Common.AuthorizationDelegatingHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) in D:\GitHub\CleanArchitecture\src\ClientApps\MauiBlazor.Shared\Common\Authoriz07-16 12:39:49.025 I/DOTNET  (16085):    at MauiBlazor.Share
[DOTNET] d.Services.UserService.LoginAsync(LoginModel loginModel) in D:\GitHub\CleanArchitecture\src\ClientApps\MauiBlazor.Shared\Services\UserService.cs:line 132
[DOTNET]    at MauiBlazorApp.Components.IdentityComponents.LoginComponent.HandleValidSubmitAsync() in D:\GitHub
[DOTNET] \CleanArchitecture\src\ClientApps\MauiBlazorApp\MauiBlazorApp\Components\IdentityComponents\LoginComponent.razor.cs:line 51

There is no CORS issue because the API app is allowing any origin as follows:

services.AddCors(options =>
{
    options.AddPolicy(myAllowSpecificOrigins, builder =>
    {
        builder
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials()
        .SetIsOriginAllowed(_ => true);
    });
});

Please help me how can I overcome the issue so that I can make requests to the ASP.NET Core REST endpoints from .NET MAUI Blazor app successfully. Thanks in advance.

Activity

  1. Eilon commented on Jul 19, 2021

    @Eilon
    Contributor

    Hi @tanvirarjel can you share more info about this setup? Is it all on Windows, with .NET MAUI targeting WinUI, and the ASP.NET Core server is running locally on the same Windows machine?

  2. tanvirarjel commented on Jul 19, 2021

    @tanvirarjel
    Author

    @Eilon Here is the complete repo: https://github.com/TanvirArjel/CleanArchitecture

    Is it all on Windows, with .NET MAUI targeting WinUI, and the ASP.NET Core server is running locally on the same Windows machine?

    Yes! It's on Windows. Both servers are running on Windows local machine.

  3. Eilon commented on Jul 19, 2021

    @Eilon
    Contributor

    BTW CORS shouldn't matter here because CORS applies only to browsers making calls to a remote server. In this case it's a .NET Core app making a call, so CORS isn't a factor one way or another.

  4. Eilon commented on Jul 19, 2021

    @Eilon
    Contributor

    The first thing that I can think of is some issue related to HTTP vs. HTTPS. Is everything consistently using HTTPS in this scenario?

  5. tanvirarjel commented on Jul 19, 2021

    @tanvirarjel
    Author

    @Eilon

    Is everything consistently using HTTPS in this scenario?

    I think so. It would be great if you run the repository on your machine and test.

  6. Eilon commented on Jul 19, 2021

    @Eilon
    Contributor

    @tanvirarjel in that case it will likely take a while for me to get to this because it could involve a lot of investigation. Ideally we have minimal repro projects for this so there are fewer possible problems.

  7. tanvirarjel commented on Jul 21, 2021

    @tanvirarjel
    Author

    @Eilon Okay! I shall provide a minimal repo soon.

  8. tanvirarjel commented on Aug 5, 2021

    @tanvirarjel
    Author

    @Eilon Here is the minimal repo to reproduce the issue: https://github.com/TanvirArjel/MauiDemo. After running both API and MAUI Blazor app in debug mode, please click on the FetchData menu and see the debug output.

    This has been an irritating issue as this blocked my MAUI learning. Please let me know the update.

    Thanks in advance.

  9. tanvirarjel commented on Aug 19, 2021

    @tanvirarjel
    Author

    @Eilon Could you please give me an update on this issue?

    Thank you.

  10. Eilon commented on Aug 19, 2021

    @Eilon
    Contributor

    Hi @tanvirarjel I updated your project to be compatible with preview7/RC1 and it seems to work just fine for me. First I started the ASP.NET Core server so that the API would run on port 44393 (using HTTPS), then I deployed the WinUI project and ran it from the Start Menu (there's a bug right now in VS where you can't run the WinUI app directly), and it was able to do the HttpClient call to get the weather forecast.

    image

    You can see the changes I made to the app here: tanvirarjel/MauiDemo#1

    (I only changed things that changed in MAUI/Blazor/WinUI, I didn't change any app code.)

  11. tanvirarjel commented on Aug 19, 2021

    @tanvirarjel
    Author

    @Eilon Great to hear that. I shall test the same project and get back to you.

    Thank you again.

  12. Eilon commented on Aug 19, 2021

    @Eilon
    Contributor

    Do you know if you have the ASP.NET Core HTTPS developer certificate installed?

    Check out this post from Scott Hanselman: https://www.hanselman.com/blog/developing-locally-with-aspnet-core-under-https-ssl-and-selfsigned-certs

    You might need to run this command line tool: dotnet dev-certs https --trust

  13. tanvirarjel commented on Aug 20, 2021

    @tanvirarjel
    Author

    @Eilon I see, you have only tested with MAUI Blazor Windows UI and you did not check with MAUI Blazor Android app. For windows UI its working fine but for the MAUI Blazor Android it's not working and throwing the same error:

    image

  14. tanvirarjel commented on Aug 20, 2021

    @tanvirarjel
    Author

    @Eilon Please keep me updated after testing on your machine. This is a very crucial issue which blocked my MAUI development.

  15. Eilon commented on Aug 20, 2021

    @Eilon
    Contributor

    Oh, I see. There's probably something that needs to be done in Android to make the cert trusted. The cert trust is done on the client, so when you run the command line tool, that makes Windows trust it. But Android is using a different cert store.

  16. 34 remaining items

  17. simonrozsival commented on Jun 6, 2022

    @simonrozsival
    Member

    A fix for this issue has been shipped with MAUI GA.

  18. Eagle3386 commented on Jun 15, 2022

    @Eagle3386

    @simonrozsival Just to clarify things for MAUI (Blazor) consumers like me:

    Doing

    ServerCertificateCustomValidationCallback = (request, certificate, chain, errors) =>
      "CN=localhost".Equals(certificate?.Issuer, StringComparison.OrdinalIgnoreCase)
      || errors == System.Net.Security.SslPolicyErrors.None

    inside my MauiProgram.cs is supposed to result in a NRE due to the native Android handler getting called (stack trace excerpt):

    in System.Net.Http.HttpClientHandler.InvokeNativeHandlerMethod
    in System.Net.Http.HttpClientHandler.SetServerCertificateCustomValidationCallback
    in System.Net.Http.HttpClientHandler.set_ServerCertificateCustomValidationCallback
    

    as is pointed out over at Bypass the certificate security check where it states:

    // This method must be in a class in a platform project, even if
    // the HttpClient object is constructed in a shared project.

    , right?

    If so, why do the aforementioned docs then state I should do new HttpClientHandler(); in that platform-specific class, i. e. Platforms\Android\MainApplication.cs, when in reality I explicit must instantiate new AndroidMessageHandler(); in that very class? Because I tried & only prevented the NRE with the latter handler…

    Moreover, since you stated in #68898 that

    [...] the native handlers will use the ServerCertificateCustomValidationCallback property in .NET 7 (see dotnet/android#6665, mac/iOS is implementation is currently in progress) [...]

    I'm totally confused how to set/overwrite the callback for debug purposes according to "current best practices".

    Up to your comment, I was using this SO answer's solution to circumvent the Android Emulator failing the certificate validation.

    Therefore, any help, i. e. clarification on proper ServerCertificateCustomValidationCallback usage for MAUI, would be greatly appreciated! 😉

  19. simonrozsival commented on Jun 15, 2022

    @simonrozsival
    Member

    @Eagle3386 hi! You shouldn't get any NRE exception. The HttpClientHandler class is a proxy for AndroidMessageHandler on Android so there shouldn't really be any difference.

    I tried reproducing it locally in a new MAUI Blazor project and I didn't get any NRE. Can you send me a minimum reproducible example based on a new MAUI Blazor app project?

  20. danch15 commented on Jun 16, 2022

    @danch15

    @simonrozsival I use Microsoft.AspNetCore.SignalR.Client.HubConnection and the DangerousTrustProvider and DangerousAndroidMessageHandlerEmitter Class, which can be started normally on Android 11, but the same code cannot be started on Android 7.1.2. (Windows Machine is OK too.)
    See: https://stackoverflow.com/questions/71047509/trust-anchor-for-certification-path-not-found-in-a-net-maui-project-trying-t

    private HubConnection Connect(string urls, CookieCollection authCookie)
    {
        return new HubConnectionBuilder().WithUrl(urls,
            options =>
            {
                options.Cookies.Add(authCookie);
                options.WebSocketConfiguration = conf =>
                {
                    conf.RemoteCertificateValidationCallback = (message, cert, chain, errors) => { return true; };
                };
            })
            .WithAutomaticReconnect()
            .Build();
    }
    <PropertyGroup>
    	<AndroidHttpClientHandlerType Condition="$([MSBuild]::GetTargetPlatformIdentifier('$(TargetFramework)')) == 'android'">DangerousAndroidMessageHandler, DangerousAndroidMessageHandler</AndroidHttpClientHandlerType>
    </PropertyGroup>

    The ServerCertificateCustomValidationCallback seems to have no practical effect on Android System.

    By the way, the httpClient.PostAsync can be started on Android 7.1.2 and 11 if I use the DangerousTrustProvider and DangerousAndroidMessageHandlerEmitter Class. But the HubConnection cannot be started in Android 71.2, I got the Exception:

    {System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request).
       at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
       at Microsoft.AspNetCore.Http.Connections.Client.Internal.SendUtils.SendMessages(Uri sendUrl, IDuplexPipe application, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken)
       at System.IO.Pipelines.Pipe.GetReadResult(ReadResult& result)
       at System.IO.Pipelines.Pipe.GetReadAsyncResult()
       at System.IO.Pipelines.Pipe.DefaultPipeReader.GetResult(Int16 token)
       at Microsoft.AspNetCore.SignalR.Client.HubConnection.HandshakeAsync(ConnectionState startingConnectionState, CancellationToken cancellationToken)
       at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsyncCore(CancellationToken cancellationToken)
       at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsyncCore(CancellationToken cancellationToken)
       at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsyncInner(CancellationToken cancellationToken)
       at System.Threading.Tasks.ForceAsyncAwaiter.GetResult()
       at Microsoft.AspNetCore.SignalR.Client.HubConnection.StartAsync(CancellationToken cancellationToken)
       at MauiHubConnDemo.HubHelper.ConnectWithRetryAsync(HubConnection connection) in D:\Project\notshell\HubHelper.cs:line 57}
    

    My Example code see here: https://github.com/danch15/MauiAndDevDemo/blob/main/MauiHubConnDemo.rar

    ================================================================================
    It seems like the problem is "options.Cookies.Add(authCookie);", I add a webserver with signalR, then connect to it without cookie, it OK.

  21. Eagle3386 commented on Jun 16, 2022

    @Eagle3386

    @Eagle3386 hi! You shouldn't get any NRE exception. The HttpClientHandler class is a proxy for AndroidMessageHandler on Android so there shouldn't really be any difference.

    @simonrozsival Alright, that's how I thought it ought to work. Thanks for the clarification! 👍🏻

    I tried reproducing it locally in a new MAUI Blazor project and I didn't get any NRE. Can you send me a minimum reproducible example based on a new MAUI Blazor app project?

    Of course, but I'm having a really hard time producing such a POC: instead of the NRE, I'm constantly getting Java.Security.Cert.CertificateException: 'The remote certificate was rejected by the provided RemoteCertificateValidationCallback.' with the POC's code running inside the Android Emulator.
    Though, researching that exception leads to numerous sources all telling me it's Xamarin's fault due to including the root cert while it's specified that it should be excluded, etc.

    Can you help me yet again?

  22. Eilon commented on Jun 16, 2022

    @Eilon
    Contributor

    Hi everyone, I created a little helper class that I started using that works on Android and Windows to connect to "local" SSL: https://gist.github.com/Eilon/49e3c5216abfa3eba81e453d45cba2d4

    And here's how you can use it to call from an Android emulator to a Windows-hosted ASP.NET Core app:

            var devSslHelper = new DevHttpsConnectionHelper(sslPort: 7155);
            var http = devSslHelper.HttpClient;
            var responseText = await http.GetStringAsync(devSslHelper.DevServerRootUrl + "/someApi");

    And to use SignalR client in .NET MAUI, here's how I use the helper:

            var devSslHelper = new DevHttpsConnectionHelper(sslPort: 7155);
    
            var hubConnection = new HubConnectionBuilder()
    #if ANDROID
                .WithUrl(devSslHelper.DevServerRootUrl + "/myhub"
                    , configureHttpConnection: o =>
                    {
                        o.HttpMessageHandlerFactory = m => devSslHelper.GetPlatformMessageHandler();
                    }
                    )
    #else
                .WithUrl(devSslHelper.DevServerRootUrl + "/myhub")
    #endif
                .Build();
    
            hubConnection.On<SomeThing>("SomeApi", ...);
    
            await hubConnection.StartAsync();

    It seems that to make it work on Android, there are two places in the handler that need to make the SSL checks go through:

    1. You need a ServerCertificateCustomValidationCallback that bypasses cert checks for localhost
    2. You need an IHostnameVerifier that reports that the 10.0.2.2 host is valid (that's how Android talks to the Windows host)
  23. Eagle3386 commented on Jun 16, 2022

    @Eagle3386

    @Eilon while that's an awesome helper for local debugging purposes, my scenario differs in that my service, i. e. HttpClient's target, is
    a) already hosted on a publicly available server (think of sub.example.net)
    b) has a valid wildcard certificate (i. e. *.example.net, for which my company even paid instead of using a Let's Encrypt one & that has the intermediate CA "Sectigo RSA Domain Validation Secure Server CA" & the root CA "USERTrust RSA Certification Authority")
    c) my set ServerCertificateCustomValidationCallback enters with errors already being set to RemoteCertificateChainErrors

    And according to

    https://github.com/xamarin/xamarin-android/blob/3d5231ca3a094b85302b5dbd3cc074be37efa2c0/src/Mono.Android/Xamarin.Android.Net/X509TrustManagerWithValidationCallback.cs#L56-L60

    (Inline code preview seems to be prevented for cross-linked repos…)

    that error is only set if the internal TrustManager threw an exception - which I neither see at VS's debug outputs nor within the Android Emulator, hence I simply don't know what actually failed within the remote certificate chain. 😢

  24. Eilon commented on Jun 16, 2022

    @Eilon
    Contributor

    @Eagle3386 ah alright that might very well be different. My helper is only for locally hosted sites (e.g. ASP.NET Core running on your Windows machine).

  25. Eilon commented on Jun 16, 2022

    @Eilon
    Contributor

    I started a discussion topic on how to connect from Android emulators to a local ASP.NET Web API running on Windows: dotnet/maui#8131

    Please check that out and let us know if you have any feedback on any of the solutions presented.

  26. Eagle3386 commented on Jun 17, 2022

    @Eagle3386

    @Eilon & @simonrozsival I still implemented Eilon's snippet nonetheless, but its CustomHostnameVerifier isn't even reached: the CustomAndroidMessageHandler's assigned ServerCertificateCustomValidationCallback value is accessed first & since I'm in scenario 4 mentioned over at dotnet/maui#8131 (remote test server & real SSL certificate) the shouldn't ever happen, right?

    Also, I did notice these debug output lines in VS (Callback.NRE is my current attempt for Simon's initial POC request):

    Resolved pending breakpoint at 'HttpsHelper.cs:38,1' to bool Callback.NRE.HttpsHelper.<>c.<GetPlatformMessageHandler>b__12_0 (System.Net.Http.HttpRequestMessage message, System.Security.Cryptography.X509Certificates.X509Certificate2 cert, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors errors) [0x00000].
    [EngineFactory] Provider GmsCore_OpenSSL not available
    

    Is my RemoteCertificateChainErrors caused due to missing OpenSSL?
    Though, I'm running the Android Emulator's default image for Android 11...

    Furthermore, ChainStatus is empty, so I'm still unable to determine the real cause:
    image

    Lastly, please let me know if I should post this over at the mentioned discussion instead of this issue. I'd almost do anything just to get this chain error resolved… 😅

  27. Eagle3386 commented on Jun 21, 2022

    @Eagle3386

    Just for the sake of completeness: using @Eilon's helper helped (pun intended! 😎) solve the NRE issue & also enabled me to discover that ASP.NET Core's dev cert was included in the chain - although "invisible" as anyone can see in my screenshot above (showing 3 instead of 4 certs).

    Everything else was/is discussed over at dotnet/maui/discussions/8131.

  28. ghost locked as resolved and limited conversation to collaborators on Aug 18, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions