ASP.NET MVC Global authentication and AllowAnonymous

Viewed 157

I'm fairly new to ASP.NET MVC and trying to understand global Authentication Filters and anonymous access.

I have a custom AuthenticationFilter as so:

public class CustomAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext filterContext)
    {
        //Do some stuff
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
    {
        var user = filterContext.HttpContext.User;
        if (user == null || !user.Identity.IsAuthenticated)
            filterContext.Result = new HttpUnauthorizedResult();
    }
}

...and I've added it in my FilterConfig.cs to become global, as so:

filters.Add(new CustomAuthorizationAttribute());

When the app loads, it gets stuck in a circular loop - the login page just keeps redirecting.

The login page has the AllowAnonymous attribute. AllowAnonymous skips the AuthorizationAttribute step, so understandably doesn't impact the Authentication Filter.

My questions are:

1) If the Authentication scope is to verify the user, surely AllowAnonymous should bypass the AuthenticationFilter step instead? Once you've passed authentication, you're no longer anonymous...please can someone explain what I'm missing?

2) If I want to lock down a site, am I on the right track to have a global Authentication Filter? If so, how do I get out of this infinite loop and allow the login page to be shown?

Thanks!

0 Answers
Related