0

I have several .NET core API and I use IdentityServer 4 as a seperate service for authentication.

The problem is that in "debug" I also wish to run my API without authentication (without launching the IdentityServer).

So, I try to bypass it... I have try several solutions, but none work: - With a AuthorizationHandler: Bypass Authorize Attribute in .Net Core for Release Version - With a Middleware : Simple token based authentication/authorization in asp.net core for Mongodb datastore - With a filter : ASP.NET Core with optional authentication/authorization - With AllowAnonymousFilter : Bypass Authorize Attribute in .Net Core for Release Version

But no way, none of theses solutions work, I still got a "401 Undocumented Error: Unauthorized" !

Here is some parts of my code:

public void ConfigureServices(IServiceCollection services)
{
    // JSON - setup serialization
    services.AddControllers().
        AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter(new TargetSpot.Core.Json.SnakeCaseNamingStrategy()));
            options.JsonSerializerOptions.IgnoreNullValues = true;
        });

    // Force lowercase naming
    services.AddRouting(options => options.LowercaseUrls = true);

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Setup the connection to the IdentityServer to request a token to access our API
    services.AddAuthentication(IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationDefaults.AuthenticationScheme)
    .AddIdentityServerAuthentication(options =>
    {
        options.Authority = Configuration.GetSection("APISettings")["AuthorityURL"];
        options.RequireHttpsMetadata = false;
        options.ApiName = Configuration.GetSection("APISettings")["APIName"];
    });

    // Add swagger
    services.AddSwaggerGen(options =>
    {
        //options.DescribeAllEnumsAsStrings();
        options.SwaggerDoc("v1", new Microsoft.OpenApi.Models.OpenApiInfo
        {
            Title = "HTTP API",
            Version = "v1",
            Description = "The Service HTTP API",
            TermsOfService = new Uri("http://www.myurl.com/tos")
        });

        // XML Documentation
        var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, xmlFile);
        options.IncludeXmlComments(xmlPath);
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
        app.UseHsts();
    }

    app.UseRouting();

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

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

    app.UseSwagger().UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "Winamp API v1");
    });
}
1
  • 2
    have you tried to just remove [Authorize] attribute on your api controller? Commented Nov 5, 2019 at 3:05

2 Answers 2

0

I had similar problem. AllowAnonymousFilter works in ASP.NET Core 2.2 but not in ASP.NET Core 3.x. After day of investigation I have found out that switching from UseEndpoints to UseMvc solved it and I can now disable authentication without commenting out [Authorize] attributes.

It seems that UseEndpoints does not use filter when registered by AddMvc but how to correctly register it when using UseEndpoints I do not know.

My solution Startup.ConfigureServices:

services.AddMvc(o =>
{
    o.EnableEndpointRouting = false;
    o.Filters.Add(new AllowAnonymousFilter());
});

Startup.Configure:

// anonymous filter works with UseMvc but not with UseEndpoints
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller}/{action=Index}/{id?}");
});

//app.UseEndpoints(endpoints =>
//{
//    endpoints.MapControllerRoute(
//        name: "default",
//        pattern: "{controller=Home}/{action=Index}/{id?}");
//});
Sign up to request clarification or add additional context in comments.

Comments

0

I found the solution in this link: https://docs.identityserver.io/_/downloads/en/latest/pdf/. Obviously I had to remove the Authorize attributes I added manually in my controllers.

app.UseEndpoints(endpoints =>
{
    // Allowing Anonymous access to all controllers but only in Local environment
    if (env.IsEnvironment(Constants.ApplicationConstants.LocalEnvironment))
        endpoints.MapControllers();
    else
        endpoints.MapControllers().RequireAuthorization();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.