How require authorization within whole ASP .NET MVC application

限于喜欢 提交于 2019-11-27 08:51:51

Simplest way is to add Authorize attribute in the filter config to apply it to every controller.

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());

        //Add this line
        filters.Add(new AuthorizeAttribute());
    }
}

Another way is to have all of your controllers inheriting from a base class. This is something I do often as there is almost always some shared code that all of my controllers can use:

[Authorize]
public abstract class BaseSecuredController : Controller
{
    //Various methods can go here
}

And now instead of inheriting from Controller, all of your controllers should inherit this new class:

public class MySecureController : BaseSecuredController
{
}

Note: Don't forget to add AllowAnonymous attribute when you need it to be accessible to non-logged in users.

To build upon DavidG's answer, if you need to require a certain role (in Windows authentication, for example, where everyone is authorized) you can do this:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());

        filters.Add(new AuthorizeAttribute { Roles = "MyApp Access" });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!