How to allow an anonymous user access to some given page in MVC?

前端 未结 2 1728
臣服心动
臣服心动 2020-11-30 03:38

I have enabled form authentication in my ASP.NET MVC web application. I want to allow anonymous users access only to some specific pages, including Register.cshtml for inst

2条回答
  •  时光说笑
    2020-11-30 04:30

    In MVC you normally use the [Authorize] attribute to manage authorization. Controllers or individual actions that are dressed with that attribute will require that the user is authorized in order to access them - all other actions will be available to anonymous users.

    In other words, a black-list approach, where actions that require authorization are black-listed for anonymous users using [Authorize] - all actions (not dressed with the attribute) will be available.

    Update:

    With MVC4 a new attribute has been introduced, namely the [AllowAnonymous] attribute. Together with the [Authorize] attribute, you can now take a white-list approach instead. The white-list approach is accomplished by dressing the entire controller with the [Authorize] attribute, to force authorization for all actions within that controller. You can then dress specific actions, that shouldn't require authorization, with the [AllowAnonymous] attribute, and thereby white-listing only those actions. With this approach, you can be confident that you don't, by accident, forget to dress an action with the [Authorize], leaving it available to anyone, even though it shouldn't.

    Your code could then be something like this:

    [Authorize]
    public class UserController : Controller {
    
       [AllowAnonymous]
       public ActionResult LogIn () {
          // This action can be accessed by unauthorized users
       }
    
       public ActionResult UserDetails () {
          // This action can NOT be accessed by unauthorized users
       }
    }
    

提交回复
热议问题