Setting multiple global authorization policies on ASP.Net Core controller by route?

1.1k Views Asked by At

Working with an ASP.Net Core API. There is one route (api/) for the regular application, another one (admin/) for the admin api's. Is there a way to set different global policies based on the URL?

This article Setting global authorization policies using the DefaultPolicy and the FallbackPolicy in ASP.NET Core 3.x talks about how to set global authorization on different parts of the application (MapRazorPages, MapHealthChecks, etc).

The MapHealthChecks has a parameter for the routes the policy is to be applied. MapControllers() does not take any parameters. Is it possible to do the same things on a controller?

1

There are 1 best solutions below

0
On

The custom policy can be specified separately for each area:

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("ApiPolicy", policy =>
    {
        policy.RequireAuthenticatedUser();
        policy.RequireClaim("scope", "api");
    });
});
...
app.MapControllerRoute(
    name: "Api",
    pattern: "api/{controller=Home}/{action=Index}/{id?}")
.RequireAuthorization("ApiPolicy");