Starting with .Net 6
we can do this (if using minimal hosting model recommended by Microsoft):
app
.MapControllers()
.RequireAuthorization(); // This will set a default policy that says a user has to be authenticated
Starting with .Net Core 3
we can do this:
app.UseEndpoints(endpoints =>
{
endpoints
.MapControllers()
.RequireAuthorization(); // This will set a default policy that says a user has to be authenticated
});
It is possible to change default policy or add a new policy and use it as well.
P.S. Please note that even though the method name says “Authorization”, by default it will only require that the user is Authenticated. It is possible to add more policies to extend the validation though.