views:

28

answers:

1

I want to use the standard AuthorizeAttribute (i.e. not inherit it) but with a custom redirect. Is that possible? where should I check for 401 and redirect?

I've tried to add

<customErrors mode="On" > 
       <error statusCode="401" redirect="/Errors/NotAuthorized/" /> 
</customErrors> 

but it didn't work.

A: 

Did this in my ApplicationController:

    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        var attributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(AuthorizeAttribute), true);
        if (attributes.Length == 0)
            attributes = GetType().GetCustomAttributes(typeof(AuthorizeAttribute), true);
        if (attributes.Length == 0)
            return;

        foreach (AuthorizeAttribute item in attributes)
        {
            if (!Thread.CurrentPrincipal.IsInRole(item.Roles))
            {
                filterContext.Result = new RedirectResult("/Errors/Unauthorized");
            }
        }
    }

I'll award anyone who has a better solution.

jgauffin