user20081580
user20081580

Reputation:

Consuming web api with JWT authentication in .NET 7 MAUI?

I have a minimal API .NET 7 installed on an external web server and use JWT for authentication. For testing I created a few endpoints (with authentication and also without) so I can test the web API via Postman. I start Postman from my private machine and access the web address of the API to test everything.

Now everything works as expected. I can log in via Postman, then I get JWT and if I enter JWT in Postman, then I can also access protected endpoint and get the data from the Web API.

Now I have created a desktop application in MAUI .NET 7 and I want to use this web API. Also here the access to unprotected endpoint works as well as logging in with receiving the JWT. Only the last part of the whole thing does not work anymore and that is access to a protected endpoint with the delivery of JWT for which I constantly get the message 401 Unauthorized. If I then put the same JWT into Postman, then the request goes through Posstman and I get the data from Web API!

I have been looking for a solution and have tried all possible code examples from the internet. For example:

        var requestMessage = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri("http://api.mywebsite.com:64591/secret")
        };
        requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", Token.token);
        var response = await _httpClient.SendAsync(requestMessage);

or

        _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Token.token);
        var RawData = await _httpClient.GetStringAsync("http://api.mywebsite.com:64591/secret2");

In some places I read that there were problems with the change to .NET 6. The solution was new NuGet packages, but since I'm already on .NET 7, I installed the latest versions.

There was also a post suggesting that in the web API you set issuer and audience to false. I did that as well, but to no success.

            ValidateIssuer = false,
            ValidateAudience = false,

Does anyone have a working code for MAUI native app that consumes minimal API?

EDIT

Following Heretic Monkey's suggestion, I installed Wireshark software and analyzed Network Transfer.

Here is what I found:

Hypertext Transfer Protocol
    HTTP/1.1 401 Unauthorized\r\n
        [Expert Info (Chat/Sequence): HTTP/1.1 401 Unauthorized\r\n]
            [HTTP/1.1 401 Unauthorized\r\n]
            [Severity level: Chat]
            [Group: Sequence]
        Response Version: HTTP/1.1
        Status Code: 401
        [Status Code Description: Unauthorized]
        Response Phrase: Unauthorized
    Transfer Encoding: chunked\r\n
    Server: Microsoft-IIS/10.0\r\n
    WWW-Authenticate: Bearer error="invalid_token"\r\n
    X-Powered-By: ASP.NET\r\n
    Date: Sun, 18 Dec 2022 09:07:00 GMT\r\n
    \r\n
    [HTTP response 1/1]
    [Time since request: 0.047969000 seconds]
    [Request in frame: 790]
    [Request URI: http://api.myserver.com:64591/secret2]
    HTTP chunked response
        End of chunked encoding
            Chunk size: 0 octets
        \r\n
    File Data: 0 bytes

There are only two error reasons I could think of:

  1. I still have a bug in my minimal API (Web Api) and that is regarding the JWT I get from the client and somehow still need to convert/crimp the JWT maybe!? By the fact that I may use JWT in exactly the form that is sent to client, then it may be that it is wrong and that is why this error message "invalid_token" comes.
  2. the second cause could be NET 7, so an error that occurs not because my code is wrong but because it is implemented incorrectly in NET 7 (is of course not probable but not impossible).

Maybe someone has a suggestion how I can fix this error?

If this doesn't work (i.e. a request to Web Api with JWT authentication), then Web Api is unusable in NET 7 and I really can't imagine that.

So I truly assume that the bug is in my implementation (either server/minimal Api or client MAUI NET 7).

Thanks

Upvotes: 0

Views: 4325

Answers (3)

Sorina Moza
Sorina Moza

Reputation: 1

I had exactly the same problems with the API and it just didn't work whatever I tried. I tested in postman all the domains and all types of json/text content, I disabled the firewall, I set it to ignore ssl certificates and nothing. But, I succeeded with Jexus Manager. You install it and connect to the server through the application solution. There at the API you create a new connection for https and mention the internet ip. Then run the API with the https domain and make sure to use https and the port from swagger in the code. The URL should be of the form "https://10.0.2.2:swagger_port_for_https/api/yourcontroller". It still doesn't make sense to me why this works and other options don't, but this works.

Steps in Jexus: File-> Connect to a server->Server type: Visual Studio IIS Express->choose the .sln ->Config source: visual studio-> connection name: localhost-> select your api from localhost and there you have Bindings in Actions. There you can edit you https or add new url for the localhost

Upvotes: 0

Ali Hussein
Ali Hussein

Reputation: 1

In my case I noticed that

response.Content.ReadAsStringAsync().Result 

in .NET MAUI will return "+token+", I have trimmed the quotation mark (") , and it worked with me

using HttpResponseMessage response = await client.PostAsJsonAsync("Login", loginData);

response.EnsureSuccessStatusCode();
string token =   response.Content.ReadAsStringAsync().Result;

Upvotes: 0

user20081580
user20081580

Reputation:

The problem was already kind of strange, because even the many tutorials and posts in the form as they are given in Internet will not work. But if you copy generated token out (e.g. from debug mode) and use it in Postman, then everything will work nicely and this is something that confuses you a lot. Fortunately, there are still people who have incredible mind and can detect such inconsistencies. I wouldn't have seen this in 1000 years either :)

See: https://learn.microsoft.com/en-us/answers/questions/1133200/401-unauthorized-consuming-web-api-with-jwt-authen.html

Upvotes: 0

Related Questions