Question

How do I achieve authorization with MVC asp.net?

Was it helpful?

Solution

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

OTHER TIPS

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.

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.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top