0

I have a custom AuthorizeAttribute on my actions in a asp.net mvc web api. I need to inject my EF ObjectContext into it.

First request after the dev server fires up always works. It's the following ones that fail. The ObjectContext is disposed and for the life of me I can't figure out how to inject the damn thing for every request.

Here is my FilterProvider.

   public class UnityFilterAttributeFilterProvider : IFilterProvider
    {
        public UnityFilterAttributeFilterProvider(IUnityContainer container)
        {
            _container = container;
        }

        private IUnityContainer _container;


        public IEnumerable<Filter> GetFilters(HttpConfiguration configuration, HttpActionDescriptor actionDescriptor)
        {
            if (configuration == null)
            {
                throw Error.ArgumentNull("configuration");
            }
            if (actionDescriptor == null)
            {
                throw Error.ArgumentNull("actionDescriptor");
            }

            IEnumerable<Filter> first =
                actionDescriptor.ControllerDescriptor.ControllerType.GetCustomAttributes(true)
                    .Select(instance => new Filter((IFilter)instance, FilterScope.Controller));

            IEnumerable<Filter> second =
                from instance in actionDescriptor.GetFilters()
                select new Filter(instance, FilterScope.Action);

            foreach (var filter in first.Concat(second))
            {
                if (filter.Instance is HeroineAuthorizeAttribute)
                    _container.BuildUp(filter.Instance as HeroineAuthorizeAttribute);
            }


            return first.Concat(second);
        }
    }

_container.BuildUp is called on the first request but not for subsequent.

When that didn't work, I doubled up with an ApiControllerActionInvoker. Here it is:

 public class InjectingActionInvoker : ApiControllerActionInvoker
    {
        private readonly IUnityContainer _container;

        public InjectingActionInvoker(IUnityContainer container)
        {
            _container = container;
        }

        public override System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
        {
            foreach (var filter in actionContext.ActionDescriptor.GetFilters())
            {
                if (filter is HeroineAuthorizeAttribute)
                {
                    var f = filter as HeroineAuthorizeAttribute;
                    f.UserRepository = _container.Resolve<IUserRepository>();
                }

            }
            return base.InvokeActionAsync(actionContext, cancellationToken);
        }
    }

Sure enough, injection takes place on the first request, not on the subsequent. But this all takes place after OnAuthorization is called so there is not much point. I thought I'd mention it anyway.

Umm... so how do I do this?

I just thought I'd show my Application_start aswell. I'm sure you can fill in the blanks.

    var container = CoinUnityContainerFactory.GetUnityContainer();

    DependencyResolver.SetResolver(new HeroineDependencyResolver(container));
    GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new HeroineServiceResolver(container));
2
  • This seems awfully complicated just for authorization. Why not use the default attribute and roll your own membership provider? May 30, 2012 at 21:17
  • The thought did strike me. But I use the UnityContainer for almost everything else so... Please indulge me, I feel I'm very close.
    – Martin
    May 30, 2012 at 21:29

1 Answer 1

1

Eventually I did roll my own membership provider, just overriding SqlMembershipProvider.

However the ObjectContext is not my main reason for my custom attribute so a custom membership provider in itself doesn't solve the problem. I'm still left with my original question, where to inject my object context, only the target has changed.

There is also the added problem of MembershipProvider being centered around MembershipUser, but I've dealt with parallel users before so that's circumvented easily enough.

Finally it all worked out with this. (See edit below.)

    public override void Init()
    {
        this.AuthorizeRequest += new EventHandler(WebApiApplication_AuthorizeRequest);
        base.Init();
    }

    void WebApiApplication_AuthorizeRequest(object sender, EventArgs e)
    {
        var provider = Membership.Provider as HeroineMembershipProvider;
        if (provider != null)
            provider.UserRepository = _container.Resolve<IUserRepository>();
    }

That's called every request and injects a fresh repo every time. My updated attribute depends on Membership.Provider and not directly on the object context.

It took a while before I realized what I was actually doing.

The thing is, I don't use FormsAuthentication. Authentication is by an encrypted ticket sent in the header. That's why I need my custom auth attribute. MVC doesn't play with cookieless auth which in essence is what I'm doing.

So I'm using Membership.Provider only as a vessel to carry a fresh object context. Seems like I might as well use HttpContext.Current.Items. That's the quick answer I suppose.

In the end, though, the new MembershipProvider allows me to clean up my code in my other non api web apps where FormsAuthentication IS used (and where, incidentally, FilterAttributeFilterProvider works as it should IMO). So I don't mind this, actually.

Anybody has a better/simpler idea or has an itch about security vulnerability I need to be reminded of, let me know.

Edit

Alot of things changed from MVC 4.0 beta to RC. Cutting the story short, I tool inspiration from this nice fellow. Creation of the MembershipProvider and injection of UserRepo now goes in the BeginScope()-method. Clean? Perhaps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.