32

How do I achieve authorization with MVC asp.net?

asleep
  • 4,054
  • 10
  • 34
  • 51

4 Answers4

54

Use the Authorize attribute

[Authorize]
public ActionResult MyAction()
{
   //stuff
}

You can also use this on the controller. Can pass in users or roles too.

If you want something with a little more control, you could try something like this.

 public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string[] users = Users.Split(',');

            if (!httpContext.User.Identity.IsAuthenticated)
                return false;

            if (users.Length > 0 &&
                !users.Contains(httpContext.User.Identity.Name,
                    StringComparer.OrdinalIgnoreCase))
                return false;

            return true;
        }
    }
Dan
  • 29,100
  • 43
  • 148
  • 207
4

There is an Authorization feature with MVC, using ASP.NET MVC beta and creating the MVC project from Visual Studio, automatically adds a controller that used authorization. One thing that will help with your google search, is that it is a "filter". So try searching on "Authorization Filter MVC" and anything preview 4 or greater will help.

MrJavaGuy
  • 676
  • 4
  • 8
  • Ah, I was just searching "ASP.NET" "MVC" Authorization and not really finding much, thanks for letting me know to search for filters. Another problem I have when searching for MVC help is that I find stuff for previous version of the preview that aren't marked as "Preview 2" etc! – asleep Dec 01 '08 at 00:23
  • I have the same problem about the some MVC posts being not marked. I usually check the date on the post, anything more then a few months ago, I consider suspect. I am going to be doing a deep dive into MVC and blogging about it. Do you have any requests? – MrJavaGuy Dec 01 '08 at 00:26
  • Yeah sure, it would be brilliant if you attempted to complete a solution using jQuery for ajax form submissions and updates instead of standard posting to a controller and returning a view! Feel free to post a link to your blog! – asleep Dec 01 '08 at 00:30
  • The jquery ajax thing wouldn't be that cool, actually. A controller action can return a JsonResult, directly (they don't always have to render a view), so the whole process is rather anticlimatic! :-) – Chris Dec 01 '08 at 01:15
  • Id like to see if a solution could be implemented in parallel in three modes: ASP.NET, WPF, and Silverlight. (I notice there's a "WPF Browser Application" type ... need to check that out ...) – dkretz Dec 01 '08 at 01:30
2

I would recommend to take a look at this article: http://kbochevski.blogspot.com/2009/11/mvc-forms-authentication-and.html

It helped me today.

Dmitry
  • 21
  • 1
0

This is how you can have authentication by default: http://mycodepad.wordpress.com/2014/03/17/mvc-secure-your-web-app/

George Kosmidis
  • 359
  • 3
  • 13