ASP.NET Core has an extensive authorization system that you can use to create complex authorization policies. In this post, I look at the various ways you can apply these policies to large sections of your application.

We’ll start by configuring a global AuthorizeFilter and see why that’s no longer the recommended approach in ASP.NET Core 3.0+. We’ll then look at the alternative, using endpoint routing, as well as using Razor Page conventions to apply different authorization policies to different parts of your app. We’ll also compare the DefaultPolicy to the FallbackPolicy see when each of them are applied, and how you can update them.

For the purposes of this post, I’ll assume you have a standard Razor Pages application, with a Startup.cs something like the following. The details of this aren’t very important, I just assume you have already configured authentication and a UI system for your application.

public class Startup
{
    public IConfiguration Configuration { get; }
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        // Configure ASP.NET Core Identity + EF Core
        services.AddDbContext<AppDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
        );

        services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<AppDbContext>();

        // Add Razor Pages services
        services.AddRazorPages();

        // Add base authorization services
        services.AddAuthorization();
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseStaticFiles();

        // Ensure the following middleware are in the order shown
        app.UseRouting();

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

        app.UseEndpoints(endpoints =>
        {
            // Add Razor Pages to the application
            endpoints.MapRazorPages();
        });
    }
}

At this point, you have authentication, and you want to start protecting your application. You could apply [Authorize] attributes to every Razor Page, but you want to be a bit safer, and apply authorization globally, to all the pages in your application. For the rest of this post, we look at the various options available.

Globally applying an AuthorizeFilter

The first option is to apply an AuthorizeFilter globally to all your MVC actions and Razor Pages. This is the approach traditionally used in earlier versions of ASP.NET Core.

#asp.net core #asp.net core identity #auth

Setting global authorization policies and the Fallback Policy in ASP.NET Core 3.x
17.20 GEEK