Question

I have a super simple Authentication Attribute that I'm trying to implement in an ASP.NET MVC 5 application and I'm having some trouble. I want the attribute to be applied globally, except for specific actions within a controller (for example the login form and the home page).

I've tried decorating the action with the [OverrideAuthentication] attribute with no luck. It gives me a redirect loop error because the application is still running the authentication on the login form, and keeps trying to redirect back to the login form over and over.

Has anyone else seen this behaviour? Any idea what I've stuffed up here?

By way of example, I've created a super simple filter that is currently unimplemented:

public class BasicAuthenticationAttribute
    : ActionFilterAttribute, IAuthenticationFilter
{

    public void OnAuthentication(AuthenticationContext filterContext)
    {
        throw new NotImplementedException();
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        throw new NotImplementedException();
    }
}

If I decorate my controller/action like this:

[BasicAuthentication]
public class AccountController : Controller
{
    [HttpGet]
    [OverrideAuthentication]
    public ActionResult Login()
    {
        return View();
    }
}

I get a not implemented exception when I navigate to the Login action, even though that action shouldn't be running the authentication code at all. Have I misunderstood how overrides are supposed to work?

Was it helpful?

Solution

I think you have confused authentication with authorization (as many people do). It doesn't make sense to make a [BasicAuthenticationAttribute] and register it globally, because authentication only happens upon login, not on every request.

Authorization is what takes place after the user has logged in to check whether the user has the required privileges to do a specific action, and it makes sense to do authorization globally. Authorization in MVC is handled by the [AuthorizeAttribute] and you can inherit it if you need to customize the way the authorization check is done. You can also register it as a global filter.

The [AllowAnonymousAttribute] works in conjunction with [AuthorizeAttribute], and basically tells it to skip the authorization check. It should also be noted that the [AllowAnonymousAttribute] will have no effect unless it is used with the [AuthorizeAttribute].

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