When I create a new asp.net mvc 4.0 application, one of the first thing I do, is create and set a custom authorize global filter
like so:
In regards to : Question 1) I was under the impression that the [AllowAnonymous] attribute would automagically bypass any code within my CustomAuthenticationAttribute but I was wrong! Do I need to manually check for the existence of the [AllowAnonymous] attribute and skip any code?
As far as I know [AllowAnonymous] attribute has nothing to do with a CustomAuthenticationAttribute. They have different purposes. [AllowAnonymous] would have an effect during an Authorization context, but not in Authentication context.
The Authentication filter has been implemented for setting up authentication context. For instance, AuthenticationContext provides you information for performing authentication. You can use this information to make authentication decisions based on the current context. For example, you may decide to modify the ActionResult to different result type based on the authentication context, or you may decide to change the current principal based on the authentication context etc.
OnAuthenticationChallenge method runs after the OnAuthentication method. You can use OnAuthenticationChallenge method to perform additional tasks on the request.
In regards to : Question 2) Why is the code inside my Index() method of my HomeController gets executed after the OnAuthentication? Only to realize that after I return View() do the code inside the OnAuthenticationChallenge() gets executed?
This is the expected behaviour. Since the you have a Globally registered Authentication filter, the very first thing is that, before any action executes, it would first fire the OnAuthentication event as you would have noticed. Then the OnAuthenticationChallenge after the Index being executed. Once the Action is succeeded any authentication filter relevant that Action (i.e Index), would run the OnAuthenticationChallenge so it can contribute to the action result. As you have in your code for OnAuthenticationChallenge you can modify the ActionResult to an HttpUnauthorizedResult this would get negotiated with the ActionResult.