Search code examples
xamarin.formsjwtasp.net-core-webapidotnet-httpclientblazor-webassembly

Asp.net Core authorization fails only for xamarin forms application


I' developed a simple app to pratice. The combination is ASP.NET CORE with JWT Token.

On my asp.net core 3.1 server, I have this DI code:

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidateAudience = true,
                        ValidateLifetime = true,
                        ValidateIssuerSigningKey = true,
                        ValidIssuer = configuration["jwt:Issuer"],
                        ValidAudience = configuration["jwt:Audience"],
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["jwt:Key"]))
                    };
                });

I can easily connect with Postman or my BlazorApp to generate a token and consume other endpoints with the token. On Blazor, I just need to insert a DefaultHeader:

_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token);

Now, I'm trying to do the same with a Xamarin Forms app. I tried to use the generated token on the default header, but I got an Unauthorized response.

To debug the Xamarin Forms app I had to change my localhost endpoint names to 127.0.0.1 (so the emulator can reach the asp.net API on my machine).

I tried to change the issuer of my JWT token to 127.0.0.1 instead localhost but no success.

Can someone help?

Thanks in advance.


Solution

  • I got it after 2 days.

    My asp.net core api was using HttpsRedirect and my Xamarin Mobile wasn't pointing to HTTPS port.

    I don't know why, because postman and blazor works with both endpoints (HTTP and https ports) but the Xamarin started working since I used the https endpoint.

    Now it's fine. Thanks anyway