wassertim
wassertim

Reputation: 3136

ASP .NET MVC Secure all resources

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?

Upvotes: 2

Views: 566

Answers (3)

Adam Jachocki
Adam Jachocki

Reputation: 2125

It's really strange that no one said about AllowAnonymous attribute which services for such situations:

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

Upvotes: 0

wassertim
wassertim

Reputation: 3136

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.

Upvotes: 1

Darin Dimitrov
Darin Dimitrov

Reputation: 1039398

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

Upvotes: 3

Related Questions