In my MVC2 application I want most requests to use Forms authentication and requests to some specific URIs to use my custom authentication. In order to do so I added FormsAuthentication_OnAuthenticate() method and inside I check the URI and if it’s one of those exclusive URIs I want to check the username and password in the request headers.
The problem is how to terminate the request if the credentials provided are wrong.
I tried:
HttpContext context = args.Context;
context.Response.Write( "Wrong credentials" );
context.Response.StatusCode = 401;
context.Response.End();
but once that happens the request is forwarded to the URI that is specified in web.config under
<authentication mode="Forms">
<forms loginUrl="~/LogOn"/>
</authentication>
I want the request to be terminated – so that the response is sent to the client and the connection is closed. How do I achieve that?
As long as you send 401 status code the Forms Authentication module intercepts this code and automatically redirects to the logon page. The correct way to handle authentication in ASP.NET MVC is using the
[Authorize]attribute. And if you don’t want it to redirect to the login page but instead show some view you could write a custom authorize attribute and override theHandleUnauthorizedRequestmethod:UPDATE:
In addition to overriding the
HandleUnauthorizedRequestyou could override the AuthorizeCore method which allows you to perform custom authentication.