Authorize in ASP.NET Core

Viewed 416

I want to implement a web project with ASP.NET Core, all pages of which require authorization.

I do not want to put the Authorize attribute on top of all controllers.

Is there a way to define this at the project level and have it applied to all pages?

1 Answers

For Razor Pages, you can just add RequireAuthorization in your configuration file (probably Startup.cs) (described by andrewlock.net).

app.UseEndpoints(endpoints =>
{
    // Require Authorization for all your Razor Pages
    endpoints.MapRazorPages().RequireAuthorization();
});

For controllers, you can do something very similar:

app.UseEndpoints(endpoints =>
{
    // Require Authorization for all your Controllers
    endpoints.MapControllers().RequireAuthorization();
});

Another simple solution for Controllers is a parent controller with a single [Authorize]:

[Authorize]
public class AuthorizedController : Controller
{
}

Then you can inherit your specific controllers, like:

public class MyController : AuthorizedController
{
}

They will all be authorized.

Related