ASP.NET MVC Authorization

50,809

Solution 1

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;
        }
    }

Solution 2

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.

Solution 3

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.

Share:
50,809
asleep
Author by

asleep

Updated on May 19, 2020

Comments

  • asleep
    asleep almost 4 years

    How do I achieve authorization with MVC asp.net?

  • asleep
    asleep over 15 years
    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!
  • MrJavaGuy
    MrJavaGuy over 15 years
    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?
  • asleep
    asleep over 15 years
    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!
  • Chris
    Chris over 15 years
    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! :-)
  • dkretz
    dkretz over 15 years
    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 ...)