Here is an example of a custom authorize attribute that you can use:
public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
and then decorate your controller action with this attribute:
[CustomAuthorizeAttribute] public ActionResult SomeAction() { ... }
Beware of an approach you should be aware of. If the user is not logged in, the server sends 200 status codes that are not very friendly to SEO. It is better to send a 401 status code. The problem is that if you use Forms Authentication, there is a custom module that is added to the ASP.NET execution pipeline and whenever the server sends the 401 status code, it is intercepted and automatically redirected to the login page. This design functionality is not a bug in ASP.NET MVC. It has always been so.
And, in fact, there is a way to overcome this unpleasant situation:
You can change the custom authorization filter as follows:
public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) {
and in Global.asax:
protected void Application_EndRequest() { if (Context.Items.Contains("unauthorized")) { Context.Response.Clear(); Context.Response.StatusCode = 401; Context.Server.Transfer("~/401.htm"); } }
Now it is better. You get a 401 status code with a custom error page. Nice.
source share