SexyMF
SexyMF

Reputation: 11185

Overriding AuthorizeCore from AuthorizeAttribute is not being invoked

For some reason, only the method OnAuthorization is being invoked, but AuthorizeCore not.
this is how I call it:

[AuthorizeWithRoles(Roles = "Affiliate")]
public string TestOnlyAffiliate()
{
     return "ok";
}

this is the actual attribute.

public class AuthorizeWithRolesAttribute : AuthorizeAttribute
{

    public string Roles { get; set; }

    //
    //AuthorizeCore - NOT INVOKING!
    //
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        return true;
    }
    public  void OnAuthorization(AuthorizationContext filterContext)
    {

    }
}

Upvotes: 5

Views: 9737

Answers (2)

user247702
user247702

Reputation: 24232

You're not supposed to override OnAuthorization. It deals with potential caching issues and calls AuthorizeCore.

http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/1acb241299a8#src/System.Web.Mvc/AuthorizeAttribute.cs

// In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page.

Put your custom logic in AuthorizationCore.

Upvotes: 10

GWthedev
GWthedev

Reputation: 19

Not sure if this helps you at all, but I ran into this same thing and determined that, at least for my purposes, I didn't need to override AuthorizeCore at all. I'm not sure why it's there, to be honest. As MSDN says, OnAuthorization is invoked "when a process requests authorization." This means that it will be invoked for any method that has your AuthorizeWithRoles attribute. You can put your custom code within OnAuthorization to check whether or not the user has permission, and since you can get the httpContext from filterContext, there's really no need for AuthorizeCore. Here's a simple example that works for me:

public class LoginRequired : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (Common.ValidateCurrentSession(filterContext.HttpContext))
        {
            //this is valid; keep going
            return;
        }
        else
        {
            //this is not valid; redirect
            filterContext.Result = new RedirectResult("/login");
        }
    }
}

I hope that helps. Besides that, obviously you'll need to declare that OnAuthorization is an override.

EDIT: I believe the base OnAuthorization method is what calls into AuthorizeCore. Since you're overriding OnAuthorization, obviously that call is lost. I believe overriding AuthorizeCore would only be relevant if you left OnAuthorization alone or if you called base.OnAuthorization(filterContext) within the overridden method.

Upvotes: -1

Related Questions