skip to Main Content

I have an Web API written based on ASP.NET 5 framework with Swagger UI.

When the user make an authenticated request to any of the endpoint, I get 404 "like if the framework is redirecting the user to a page that does not exists!" If the framework is automatically redirecting the request due to unauthorized request, I want to change that behavior to instead return 401 json response. If not, how can I change the response code from 404 to 401 as JSON response?

Here is how the Startup class look like

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();

    services.AddSwaggerGen(swagger =>
    {
        swagger.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "Student Athlete Wellness Tracker API",
            Description = "API to provide data for the Student Athlete Wellness Trackers",

        });
        swagger.AddSecurityDefinition("basic", new OpenApiSecurityScheme()
        {
            Name = "Authorization",
            Type = SecuritySchemeType.Http,
            Scheme = "basic",
            In = ParameterLocation.Header,
            Description = "Basic Authorization header using the Bearer scheme.",
        });

        swagger.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "basic"
                    }
                },
                Array.Empty<string>()
            }
        });
    });

    services.AddAuthentication("BasicAuthentication")
            .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
}


public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/error");
        app.UseHsts();
    }
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Student Athlete Wellness Trackers - v1"));

    app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

    app.UseHttpsRedirection();

    app.UseRouting();
    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

2

Answers


  1. Chosen as BEST ANSWER

    To fix the issue, I changed

    services.AddAuthentication("BasicAuthentication")
            .AddScheme<AuthenticationSchemeOptions, BasicAuthenticationHandler>("BasicAuthentication", null);
    

    to

    services.AddAuthentication(opts =>
    {
        opts.DefaultAuthenticateScheme = "BasicAuthentication";
        opts.DefaultChallengeScheme = "BasicAuthentication";
        opts.DefaultScheme = "BasicAuthentication";
        opts.AddScheme<BasicAuthenticationHandler>("BasicAuthentication", null);
    });
    

  2. I run in the same issue.

    I added the second options line and that solved the problem.

    services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                })
    

    You can read the official documentation to learn more:https://learn.microsoft.com/en-us/aspnet/core/security/authentication/?view=aspnetcore-5.0

    Example:Web api core returns 404 when adding Authorize attribute

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search