2

How to enable Authentication on whole controller and disable only for certain action methods. I want authentication for all resources. If I write something like that:

[Authorize]
public class HomeController : BaseController
{
    //This is public
    [UnAuthorized]
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        return View();
    }
    //This is private resource
    public ActionResult PrivateResource()
    {
        return View();
    }
}

Then anyone can access this resource. I need this because we have all resources are private and very few are public on our project. Do you have any ideas how to make it better way?

wassertim
  • 3,076
  • 2
  • 22
  • 39
  • Duplicate see http://stackoverflow.com/questions/2071235/overriding-controller-authorizeattribute-for-just-one-action and http://stackoverflow.com/questions/2537307/asp-net-mvc-can-i-say-authorize-rolesadministrators-on-the-controller-class – David Glenn Apr 01 '10 at 09:30
  • No. it's not the answer for my question – wassertim Apr 01 '10 at 11:01

2 Answers2

3

Organize your controllers accordingly. Have a base controller for all authenticated resources which you could annotate with the [Authorize] attribute and another one for public resources.

[Authorize]
public abstract BaseAuthenticatedController : Controller
{ }

public abstract BaseController : Controller
{ }
Darin Dimitrov
  • 960,118
  • 257
  • 3,196
  • 2,876
  • Thank you Darin. It is not what I wanted exactly. I want to be able to make certain action methods of controller to be public and rest of them private. – wassertim Apr 01 '10 at 07:18
1

Based on solution which is found here I wrote the code that fixes exactly what I wanted.

Create custom authorization attribute base on AuthorizeAttribute and override method OnAuthorization:

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext != null)
        {
            object[] attributes = filterContext.ActionDescriptor.GetCustomAttributes(false);
            if (attributes != null)
            {
                foreach (var attribute in attributes)
                    if (attribute is UnAuthorizedAttribute)
                        return;
            }
        }
        base.OnAuthorization(filterContext);
    }

I'm using a reflection here to recognize an action with UnAuthorized attribute. I don't know about performance issues in this case, but it solves the problem completely.

Community
  • 1
  • 1
wassertim
  • 3,076
  • 2
  • 22
  • 39
  • Much of this code is unnecessary. Just use ActionDescriptor.GetCustomAttributes() directly, so you can bypass using reflection to guess what the incoming method is. – Levi Apr 01 '10 at 16:55