How do I terminate request processing when implementing custom authentication in MVC?
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 r开发者_高级运维equest 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 the HandleUnauthorizedRequest
method:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Shared/unauthorized.cshtml"
};
}
}
UPDATE:
In addition to overriding the HandleUnauthorizedRequest
you could override the AuthorizeCore method which allows you to perform custom authentication.
The easier way to secure your application is to use the PrincipalPermissionAttribute
, you can apply this to the whole controller, or just actions on the controller. E.g.
[PrincipalPermission(SecurityAction.Demand, Role="Administrator")]
public class AdminController : Controller
{
...
}
or
[PrincipalPermission(SecurityAction.Demand, Role="Administrator")]
public ActionResult DeleteUser(int id)
{
...
}
You can find more information in this article.
精彩评论