flutterasp.net-corebearer-tokenasp.net-authenticationflutter-http

ASP.Net Core Bearer Authentication + flutter client


I have a problem with Bearer Authentication in ASP.NET Core 3.1 Web Api project.

I configured authentication like that:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.RequireHttpsMetadata = false;
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = true,
                        ValidIssuer = AuthHelper.Issuer,
                        ValidateAudience = true,
                        ValidAudience = AuthHelper.Audience,
                        ValidateLifetime = true,
                        IssuerSigningKey = AuthHelper.GetSymmetricSecurityKey(),
                        ValidateIssuerSigningKey = true,
                    };

                });

Also, I added [Authorize] attribute in my controller and app.UseAuthorization(); in Configure method.

I configured the request in Postman. I tried to configure authorization in the "Authorization" tab and manual way (adding "Authorization" header). The same result: I get the correct answer without any errors.

However, when I send the request from my flutter app, I get a "404 Not Found" error.

Get request from flutter app:

Map<String, String> authHeaders = <String, String>{
    'Content-Type': 'application/json; charset=UTF-8',
    'Authorization': 'Bearer $authToken'
  };
    final response = await http.get(_url, headers: authHeaders);

Any ideas? What am I missing?


Solution

  • I know what the problem is. My controller still uses Cookies authentication method (not bearer).

    Solution: Replace [Authorize] by [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

    Why request from Postman works properly?

    Postman sets cookies and remembers Cookies for other requests. So when I tested the signin controller, Postman added .AspNetCore.Identity.Application cookie to own collection.