Search code examples
c#asp.net-coreauthentication

ASP.NET Core disable authentication in development environment


Is it possible to "disable" authentication in ASP.NET Core application without changing its logic?

I have a .net website which uses an external identity server app for authentication. Anyway I would like to be able to mock the authentication when I'm developing it (ASPNETCORE_ENVIRONMENT = Development), airing access to all actions ignoring the authorization attributes.

Is it possible to do it just mocking some services in the service collection?


Solution

  • You can bypass authorization in development environment by applying AllowAnonymousAttribute to your endpoints.

    .NET 6 (ASP.NET Core 6) and newer, dotnet new webapi template
    Use AllowAnonymous method in Program.cs to apply AllowAnonymousAttribute to all controllers:

    if (app.Environment.IsDevelopment())
        app.MapControllers().AllowAnonymous();
    else
        app.MapControllers();
    

    .NET Core 3.0 - .NET 5 (ASP.NET Core 3.0-5), dotnet new webapi template
    Use WithMetadata method in Startup.Configure() to apply AllowAnonymousAttribute to all controllers:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // preceding code omitted for brevity
        app.UseEndpoints(endpoints =>
        {
            if (env.IsDevelopment())
                endpoints.MapControllers().WithMetadata(new AllowAnonymousAttribute());
            else
                endpoints.MapControllers();
        });
    }
    

    Minimal API in .NET 6 (ASP.NET Core 6) and newer, dotnet new webapi -minimal template
    Use AllowAnonymous method to apply AllowAnonymousAttribute to a minimal API endpoint:

    var hiEndpoint = app
        .MapGet("/hi", () => "Hello!")
        .RequireAuthorization();
    
    if (app.Environment.IsDevelopment())
        hiEndpoint.AllowAnonymous();
    

    Details

    endpoints and app from the examples above, both implement IEndpointRouteBuilder which has multiple Map extension methods like MapControllers() and MapGet(...) that return IEndpointConventionBuilder.

    WithMetadata (available since .NET Core 3.0) and AllowAnonymous (available since .NET 5) are extensions for IEndpointConventionBuilder and can be called upon the results of those Map methods.

    AllowAnonymousAttribute's description from the docs:

    Specifies that the class or method that this attribute is applied to does not require authorization.