0

I am trying to implement authentication using custom authentication and forms authentication.

    [AllowAnonymous]
    public ActionResult Login(string returnUrl)
    {
        ViewBag.ReturnUrl = returnUrl;
        return View();
    }

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }            
        // get result from database based on the username and password match
        switch (result)
        {
            case SignInStatus.Success:
                // set cookie 
                return RedirectToAction("Index", "Home");                
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }

The accountController looks like the above. Then I implemented a custom authentication attribute like shown below.

public class CustomAuthentication : FilterAttribute, IAuthenticationFilter
{
    public void OnAuthentication(AuthenticationContext context)
    {
        if (context.HttpContext.User.Identity.IsAuthenticated)
        {
            // hit database and check the credentials 
        }
        else
        {
            context.Result = new HttpUnauthorizedResult(); // mark unauthorized
        }
    }

    public void OnAuthenticationChallenge(AuthenticationChallengeContext context)
    {
        if (context.Result == null || context.Result is HttpUnauthorizedResult)
        {
            // redirect to login page
        }
    }
}

When I register this attribute globally in filterconfig.cs

filters.Add(new CustomAuthentication());

the control comes directly to OnAuthentication method, as the user is not authenticated, OnAuthenticationChallenge gets executed and then the control again comes back to OnAuth method. This goes on and at a point it throws an exception saying "The request filtering module is configured to deny a request where the query string is too long."

When I do the same thing by using the custom attribute on a home controller, I get the expected result as the method OnAuth only gets called once but after the login method.

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login"></forms>
</authentication>

Here is my web config for authentication. What might me the cause of such behaviour ? Am I doing the authentication in a correct way ? Thanks in advance

adiga
  • 34,372
  • 9
  • 61
  • 83
  • I'd probably look to inherit from `AuthorizeAttribute` instead of `FilterAttribute`, something like this http://stackoverflow.com/a/11494091/1663001 – DavidG Oct 05 '16 at 09:45
  • @DavidG Any reason behind inheriting from AuthorizeAttribute when I am doing Authentication ? Wouldn't that be a separate implementation altogether ? – Abhijith Ponnapally Oct 05 '16 at 10:05

0 Answers0