简体   繁体   中英

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 inte.net. 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:

  • the token I receive from Web Api after authentication, I also send in the same form when requesting to an Authorized Endpoint (so received and sent token from client are identical). My conclusion here is that the token is correct.
  • When the request with the JWT is sent from the client to the server (Web Api), I then get the error message 401. In the log I see below information with the reason Bearer error="invalid_token":
 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 (ie 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

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 (eg 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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM