views:

4317

answers:

3

How do I achieve authorization with MVC asp.net?

+1  A: 

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
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!
Shahin
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
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!
Shahin
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
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 ...)
le dorfier
+16  A: 

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
+1  A: 

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