Home > Software engineering >  Access the current environment (development, production, etc.) from within the builder setup in .NET
Access the current environment (development, production, etc.) from within the builder setup in .NET

Time:08-04

I am building an app in .NET 6 that uses authentication and policy-based authorization. Both function well. However, I need to create a way to bypass authorization within a development environment. Below is my code in program.cs.

I have created a class that disables authorization and added this to the builder builder.Services.AddSingleton<IAuthorizationHandler, DisableAuthorization>(); This works fine and all I need to do now is make it conditional upon the environment being "development." My problem is that I do not know how to get the current environment from within the builder (I do know how to do it once it has been built - e.g., app.Environment.IsDevelopment()).

I have searched online but all of the solutions I could find involve injection into the Startup() and ConfigureServices() methods - both of which have been replaced by the WebApplication.CreateBuilder in .NET 6.

What is the most efficient way to get the environment prior to building the application?

Current Code (Program.cs)

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();
builder.Services.AddServerSideBlazor();
builder.Services.AddHttpClient();
builder.Services.AddSingleton<IAppState, AppState>();
builder.Services.AddScoped<IAuthorizationHandler, IsAdminHandler>();
...


//Add authentication and register CAS as the authentication handler
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

    // Add cookie authentication
    ...

builder.Services.AddAuthorization(options =>
    {
        // Add access policies
        options.AddPolicy("IsAdmin", Policies.IsAdminPolicy());
        options.AddPolicy("IsManager", Policies.IsManagerPolicy());
        options.AddPolicy("IsUser", Policies.IsUserPolicy());
        options.AddPolicy("IsReadOnly", Policies.IsReadOnlyPolicy());

        // Add fallback authorization which blocks unauthenticated access to all pages
        // unless the [AllowAnonymous] attribute is applied to the route in the controller
        options.FallbackPolicy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
    }
);

// Disable authorization in DEV
builder.Services.AddSingleton<IAuthorizationHandler, DisableAuthorization>();

// Run the builder and return the configured application to "app" 
var app = builder.Build();


// Configure the HTTP request pipeline by adding middleware
if (app.Environment.IsDevelopment())
{
    // Use detailed exception page (for development environment only)
    app.UseDeveloperExceptionPage();

    // Require HTTPS connection.  The default HSTS value is 30 days. 
    app.UseHsts();
}
else if (app.Environment.IsProduction())
{

    // Enable standard error page
    app.UseExceptionHandler("/Error");

    // Require HTTPS connection. The default HSTS value is 30 days. 
    // You may want to change this for production scenarios, 
    // see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
else
{
    throw new GenericException("Environment has not been set or is incorrect");
}

CodePudding user response:

You can use Environment property on WebApplicationBuilder:

var isDev = builder.Environment.IsDevelopment();
  • Related