Pregunta

I am using a custom role provider in my asp.net mvc-4 web application.

In my 'CustomRoleProvider' class I extended 'RoleProvider' interface and I overrode the 'IsUserInRole', 'GetRolesForUser' and 'GetAllRoles' functions in the class. That works fine.

Now I'm trying to redirect a custom page(like: "~/Security/AccessDenied/Index") if an user try to access an action in which the user has no access. If a user try to do that by default it is redirecting to home page. To redirect my custom page I extended the 'AuthorizeAttribute' interface and I overrode 'OnAuthorization' function. But looks like the 'OnAuthorization' function never being called.

Here is my the code to extend the 'AuthorizeAttribute' interface:

public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        base.OnAuthorization(filterContext);

        if (filterContext.Result is HttpUnauthorizedResult)
        {
            filterContext.Result = new RedirectResult("~/Security/AccessDenied/Index");
        }
    }
}

Why the 'OnAuthorization' function is not being called? Need help...

¿Fue útil?

Solución

You need to apply the custom attribute to actions or controllers (or add it as a general filter for all requests). Use your custom attribute instead of the Authorize attribute.

[AccessDeniedAuthorize(Roles="Admin")] 

should work.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top