MAUI App, HTTP API Basic authentication doesn't work from mobile but works from Windows - Stack Overflow

I am using Dotnet Core 9 for MAUI app.App is basically to access the HTTP API of my Dinstar device (f

I am using Dotnet Core 9 for MAUI app. App is basically to access the HTTP API of my Dinstar device (for sending SMS etc through SIM).

API is successfully accessed from a Visual Foxpro 9.0 application using MSXML2.ServerXMLHTTP.6.0

My MAUI application, when run in Windows, it works good and I'm getting the expected reply from API. However, the same App when run from mobile, the API gives 'Unauthorized' error.

Below is the code:

var username = "abcd";
var password = "abcd@123";
//username = Uri.EscapeDataString(username);
//password = Uri.EscapeDataString(password);
string statusMsg = "";

try
{
    using (var handler = new HttpClientHandler())
    {
        // Ignore SSL certificate errors
        handler.ServerCertificateCustomValidationCallback = (message, cert, chain, errors) => true;
        handler.Credentials = new NetworkCredential(username, password);

        uri = $":5050/api/send_ussd";
        var jsonPayload = new
        {
            port = new int[] { 0 },
            command = "send",
            text = "*222#"
        };
        var jsonString = JsonSerializer.Serialize(jsonPayload);

        // Create an HttpClient
        using (var client = new HttpClient(handler))
        {
            //var byteArray = Encoding.ASCII.GetBytes($"{username}:{password}");
            //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));

            // Prepare content
            var content = new StringContent(jsonString, Encoding.UTF8, "application/json");

            // Send POST request
            var response = await client.PostAsync(uri, content);
        }
    }
}

Any idea?

As you can see, I was checking with both handler.Credentials and DefaultRequestHeaders.Authorization methods for passing username/password. Both do not work and give 'Unauthorized' error.

My App has ClearTextTraffic enabled through 'network_security_config.xml' in Resources/xml under Platforms/Android.

I tried to hit the same API end point through a browser in my mobile and it gives the expected result.

If runs successfully, the API will give the result of the USSD code *222# and generally it is the balance in the SIM. Typically like the one below.

"Main Bal Rs.109.929 expires 14/08/2025. Benefit SMS 1182 expires 18/04/2025 Benefit Data MB 66780.156 expires 18/04/2025."

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744410470a4572848.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信