Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Securing the whole ASP.NET 5 MVC 6 application

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?

like image 280
Sam Avatar asked Jan 07 '16 07:01

Sam


1 Answers

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)

like image 174
haim770 Avatar answered Oct 27 '22 05:10

haim770