Apply AuthorizeAttribute to a controller class and to action simultaneously

妖精的绣舞 提交于 2019-12-09 09:46:39

问题


Is There one way to make a [Authorize] attibute be ignored in one action in a controller class that has a Authorize attribute?

        [Authorize]
        public class MyController : Controller
        {
           [Authorize(Users="?")]//I tried to do that and with "*", but unsuccessfuly,
           public ActionResult PublicMethod()
           {
           //some code
           }

           public ActionResult PrivateMethod()
           {
           //some code
           }
        }

Just the PrivateMethod() should have authentication required, but it has been required too.

PS: I wouldn't like to make my custom authorize filter.

[]'s


回答1:


By default it's impossible - if you set [Authorize] for controller then only authenticated user can access to action.

or

You can try custom decisions: stackoverflow.




回答2:


You can use [AllowAnonymous]

 [Authorize]
 public class MyController : Controller
 {
     [AllowAnonymous]
     public ActionResult PublicMethod()
     {
           //some code
     }

     public ActionResult PrivateMethod()
     {
           //some code
     }
  }



回答3:


A solution is in this article: Securing your ASP.NET MVC 3 Application

The article talks about a white list approach where you decorate actions with a AllowAnonymous custom attribute. It requires that you extend AuthorizeAttribute and the OnAuthorization method to skip authorization checks of AllowAnonymous -actions. (The approach is credited to Levi, a security expert on the MVC team.)




回答4:


    public class MyController : Controller
    {
       [Authorize] //it will only work for the following action
       public ActionResult PublicMethod()
       {
       //some code
       }

       public ActionResult PrivateMethod()  //[Authorize] will not work for this action
       {
       //some code
       }
    }


来源:https://stackoverflow.com/questions/7113673/apply-authorizeattribute-to-a-controller-class-and-to-action-simultaneously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!