Securing the whole ASP.NET 5 MVC 6 application
Asked Answered
P

2

7

If I want to secure a particular section in my MVC app, I use [Authorize] for the ActionMethod. I also know that I can use it for the entire controller so that I don't have to specify it for each and every ActionMethod in it.

I want to require authorization globally and want to be able to allow anonymous users in only a few places. How do I require users to be authorized globally and allow anonymous users in a few ActionMethods?

Populous answered 7/1, 2016 at 7:29 Comment(0)
D
9

You can simply register AuthorizeFilter globally in your Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // configure/build your global policy
    var policy = new AuthorizationPolicyBuilder()
                          .RequireAuthenticatedUser()
                          .Build();

    services.AddMvc(x => x.Filters.Add(new AuthorizeFilter(policy)));
}

(The actual policy-building bits were taken from @Sam's own answer)

Decorator answered 7/1, 2016 at 8:3 Comment(0)
P
4

Here's the answer... In Startup class, ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc(options =>
            {
                options.Filters.Add(new AuthorizeFilter(new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build()));
            });
        }
Populous answered 7/1, 2016 at 8:24 Comment(1)
Since you marked my answer as correct. I added the relevant part of your policy-builder to my answer as well.Decorator

© 2022 - 2024 — McMap. All rights reserved.