最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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."

发布评论

评论列表(0)

  1. 暂无评论