开发者

How to do 'opt-out' authentication in ASP.NET MVC [duplicate]

开发者 https://www.devze.com 2023-03-24 02:12 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Override Authorize Attribute in ASP.NET MVC 开发者_开发问答
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Override Authorize Attribute in ASP.NET MVC 开发者_开发问答

In ASP.NET MVC, you add the [Authorize] attribute above action methods to specify that users must be authenticated (and in the specified role where appropriate) to use that method.

This is a bit like 'opt-in' authentication - I have to remember to decorate every method I want to protect, which is error-prone.

How might I specify that everything requires authentication apart from the controllers or actions that I whitelist?


Here's the basic idea. You should play with this to get the desired results - especially when some actions inside controller need authorization, some - not. As you know, each and every part of asp.net mvc framework can be customized. So is filter providing mechanism of it. First, create the IFilterProvider implementation for providing authorization filters

 public class AuthorizeFilterProvider : IFilterProvider
    {
        public List<Type> AuthorizationExcludedControllerTypes = new List<Type>();

        #region IFilterProvider Members

        public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            if (!AuthorizationExcludedControllerTypes.Contains(controllerContext.Controller.GetType()))
            {
                yield return new Filter(new AuthorizeAttribute(), FilterScope.Controller, null);
//return filter only if it is not included into AuthorizationExcludedControllerTypes list.
            }
        }

        #endregion
    }

And register filter provider into Global.asax

 protected void Application_Start()
        {
            ...

            AuthorizeFilterProvider authorizeFilterProvider = new AuthorizeFilterProvider();
            authorizeFilterProvider.AuthorizationExcludedControllerTypes.Add(typeof(HomeController));

            FilterProviders.Providers.Add(authorizeFilterProvider );

            ...

        }


By default, you can't, but see this answer for information about creating your own custom authorization attribute to do it: Override Authorize Attribute in ASP.NET MVC.

0

精彩评论

暂无评论...
验证码 换一张
取 消