0
votes

I have simple custom authentication filter:

public class MyAuthAttribute : FilterAttribute, IAuthenticationFilter
{

    public void OnAuthentication(AuthenticationContext filterContext)
    {
        filterContext.Result = new RedirectResult("Account/Login");
    }

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

There are also HomeController with Index action method and AccountController with Login action method. The Index action method uses my custom filter. When I try to call Index action method, my filter intercepts code execution and make redirect to Home/Account/Login url. Why does it happen? I expected a call of Login action in AccountController.

2

2 Answers

0
votes

You are being redirected because you don't have a condition in your filter that ensures the user is not authenticated before redirecting.

A filter runs on every request. It is up to you to put branching logic within the filter to make it conditional.

public class MyAuthAttribute : FilterAttribute, IAuthenticationFilter
{

    public void OnAuthentication(AuthenticationContext filterContext)
    {
        if (!filterContext.Principal.Identity.IsAuthenticated)
            filterContext.Result = new RedirectResult("Account/Login");
    }

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

Reference: http://jameschambers.com/2013/11/working-with-iauthenticationfilter-in-the-mvc-5-framework/

0
votes

This happens because of the way you have given the URL i.e. "Account/Login". When you do not start the URL with "/", it will check for the action method in the current controller. To redirect to the correct controller and method use - "/APPLICATION_NAME/CONTROLLER_NAME/METHOD_NAME"