Globally Require Authenticated Users By Default Using Fallback Policies in ASP.NET Core

Nice article

Scott Sauber

tldr;

You can use Fallback Policies in ASP.NET Core 3.0+ to require an Authenticated User by default. Conceptually, you can think of this as adding an [Authorize] attribute by default to every single Controller and Razor Page ONLY WHEN no other attribute is specified on a Controller or Razor Page (like [AllowAnonymous] or [Authorize(PolicyName="PolicyName")]).  See lines 9-11 below.

publicclassStartup
{
// Other Startup code omitted
publicvoidConfigureServices(IServiceCollectionservices)
{
services.AddAuthorization(options=>
{
options.FallbackPolicy=newAuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
// Register other policies here
});
// Other service registrations omitted
}
}
view raw
Startup.cs
hosted with ❤ by GitHub

https://gist.github.com/scottsauber/06950b52ca45ab0b937dc59cad19e9de#file-startup-cs-L9-L11

A Quick Lap Around the [Authorize] and [AllowAnonymous] Attributes

In ASP.NET Core (and even previously in ASP.NET), we’ve had the ability to add a [Authorize] attribute to a resource (such as a…

View original post 1,033 more words

One thought on “Globally Require Authenticated Users By Default Using Fallback Policies in ASP.NET Core

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s