How to require non-anonymous user in .Net Core?

Viewed 964

In .Net Core, the controller attribute [AllowAnonymous] lets you set a controller to allow non-logged in users to access the controller.

Is there a way to do the opposite, to require a user to be logged in? Without giving all users a role and then checking every single controller with [Authorize(Roles = "WarmBody")], I can't see how to require a login?

2 Answers

You should add custom policy filter

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc(config =>
        {
            var policy = new AuthorizationPolicyBuilder()
                         .RequireAuthenticatedUser()
                         .Build();
            config.Filters.Add(new AuthorizeFilter(policy));
        });

        //other code ...
    }

    //other code ...
}

Or set [Authorize] Attribute for each controller

Related