6

I am migrating an application from ASP.NET Web Forms to ASP.NET MVC 3. One of the central and critical pieces is currently locked away in its own directory. I have restricted unauthorized user from accessing this directory by using the following in my web.config file:

<location path="home" allowOverride="false">
  <system.web>
    <authorization>
      <deny users="?"/>
      <allow users="*"/>
    </authorization>
  </system.web>
</location>

My question is, how do I implement this same type of security in ASP.NET MVC 3? I have a hunch that it involves setting attributes on my Controller classes. However, the AuthorizeAttribute looks like it only accepts a list of user names and not an auth status (please correct me if I'm wrong). I looked at the sample ASP.NET internet application and I didn't see anything special being configured in it.

Can someone please point me in the correct direction on this?

Thanks!

Andrei Rînea
  • 20,288
  • 17
  • 117
  • 166
user208662
  • 10,869
  • 26
  • 73
  • 86

3 Answers3

5

That's correct, you'll utilize the AuthorizeAttribute, like so:

 [Authorize]
 public ActionResult AuthenticatedUsers()
 {
     return View();
 }

 [Authorize(Roles = "Role1, Role2")]
 public ActionResult SomeRoles()
 {
     return View();
 }

 [Authorize(Users = "User1, User2")]
 public ActionResult SomeUsers()
 {
     return View();
 }

As for "auth status", I'm not sure I know what you mean. It sounds like Roles would handle that authentication requirement.

  • The `[Authorize]` attriute should verify that they are generally authenticated. As I read it, that's what OP is looking for. I think he may be under the impression that the Roles parameter is required. Also, it should be noted that these attributes can be applied to the controller class itself to handle them all the same way instead of having to define it for each method. – Joel Etherton Feb 09 '12 at 16:03
0

You can still do the authorization in the web.config if you want to. Most people will move their authorize permissions to the Actions or to the entire controller (or base controller) using the [Authorize] filter.

The Authorize filter supports Roles or Users the same that the web.config does (Use of * and ? for "Authenticated" and "anonymous")

If users and roles won't do it for you check out this article on creating a custom authorize attribute:

ASP.NET MVC Custom Authorization

Community
  • 1
  • 1
Nick Bork
  • 4,831
  • 1
  • 24
  • 25
0

You will use the authorize attribute to say which users or roles will have permission to access a controller (if you put in a controller, these permissions will be setted for all actions in this controller) or a action. Look: http://build.mt.gov/2011/10/27/aspnet-mvc3-and-the-authorize-attribute.aspx. Rembember who will provide your roles (from a specific user) will be a RoleProvider, like you use with asp.net webforms.

Vinicius Ottoni
  • 4,631
  • 9
  • 42
  • 64