Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the life cycle of AuthorizeAttribute object? is it web per request or transient?

I just wanted to know the life cycle of AuthorizeAttribute and started debugging the default constructor of the AuthorizeAttribute but could't get any hit.

here is the code of custom Authorize filter.

 public class CustomAuthorizeAttribute :  AuthorizeAttribute
 {
    public CustomAuthorizeAttribute() : base()
    {
        string test = string.Empty;
    }
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        //Some code
    }
}

Anyone please help me to understand the life cycle of this AuthorizeAttribute?

Thanks

like image 465
Deepak Avatar asked Jan 08 '18 11:01

Deepak


1 Answers

This is tricky to answer, because AuthorizeAttribute is both an Attribute and an IAuthorizationFilter.

In the context of an Attribute, it is loaded when GetAttributes() is called the first time by the MVC framework. Attributes are meta-data, so it shouldn't be surprising if this is loaded before the debugger is attached.

In the context of an IAuthorizationFilter, it depends on how the filter is registered. If registered as a global filter:

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new CustomAuthorizeAttribute());
        filters.Add(new HandleErrorAttribute());
    }
}

Then it is clearly instantiated during the startup of the MVC application, and in this case the filters collection is static so is only instantiated once per startup.

If the filter is placed as an attribute on a controller or action method, that's when things get more confusing. When an action is run, the MVC framework loads any attributes that pertain to that action method using the FilterAttributeFilterProvider and executes them. In this case, there is an instance that is loaded as a IAuthorizationFilter which scans for another instance of the same class that is an Attribute.

If you need to explicitly control lifetime of the filter, then you can build your own IFilterProvider that can do just that.

But there is no way to control the lifetime of an attribute. You should just assume that it is always loaded as a singleton and there is no way to create or destroy it.

The default behavior of AuthorizeAttribute (as a filter) scans for another instance of AuthorizeAttribute (as an attribute) in order to read the user/group metadata that it contains. The filter does the heavy lifting, the attribute is just a marker. If this is too confusing, you can separate them into 2 separate classes as per Passive Attributes.

like image 78
NightOwl888 Avatar answered Nov 15 '22 08:11

NightOwl888