Policy Injection with ASP.NET MVC Controllers - asp.net-mvc

I'm running into an issue with the Policy Injection Application Block from Enterprise Library in conjunction with ASP.NET MVC.
In my ControllerFactory, I'm creating the controller and then calling PolicyInjection.Wrap on the controller. This gives me back a Transparent Proxy to the controller which manages the call handler chain.
Finally, I cast the Transparent Proxy to an IController and return it.
This seems to work well, except that none of the call handlers I've defined for my controller are executing. (For example I have a Logging Handler configured, but nothing is being logged by PIAB.)
Is my final cast messing this up somehow? How does ControllerBase.Execute() call into my controller? It seems like my proxy should be utilized. Anyone using PIAB on ASP.NET controllers?

I am using PIAB to wrap ASP.NET MVC Controllers, and I'm doing so by calling
PolicyInjection.Wrap<IController>(instance)
which will wrap the IController methods. I'm also using policy injection to wrap the IActionInvoker that gets used as well, which allows for logging the action name.
I have not had success wrapping controllers using the MarshalByRefObject wrapping, but the interface wrapping works like a charm.
If you want additional information, you could create an interface that has all the methods from IController, IActionFilter, IAuthorizationFilter, IExceptionFilter and IResultFilter and then have your controllers implement that interface. Then you could wrap your controllers as that interface and get more calls going through policy injection.
I hope that helps. If you have more specific issues please post.

Seems at least one person uses it :) - ASP.NET MVC Validation using Policy Injection Application Block in Enterprise Library (this is first result BTW)

Related

Base Controller method or Utility helper method

On my MVC app, I am planning to create a generic method for Web Api's. This can be achieved either creating methods on Base Controller or methods in Utility helper class. Which is preferred way Base controller (or) Utility Class?
And also want to know on what scenario's Base Controller is useful.
ASP.NET MVC provides several alternatives to common problems (e.g. logging, exception handling, authorization) using filters or allowing your own implementation of a certain class. Usually a base controller is not the best approach since it is very likely the framework already handles the issue by other means.
Take a look at this answer for how to deal with common problems in ASP.NET MVC: https://stackoverflow.com/a/6119341/1942895

ASP.NET MVC controllers static methods

A discussion came up at work recently about why ASP.NET MVC doesn't use static methods for its controller methods. Whilst I was on the side of the fence against using static methods, the only two arguments I could think for non-static action methods were inheritence and the ability to mock (which inheritence gives you).
What was Microsoft's design choice for non-static actions/methods over static?
While I don't know minds of those that designed the ASP.NET MVC Framework here is the big one for me:
An instance controller is instantiated once per request, multiple requests can be happening simultaneously. If a controller is static then any state on the controller is shared across all requests simultaneously. You probably don't want that. Updating that shared state becomes a minefield of locking contention, possible deadlocks and very hard to track bugs if locking isn't implemented properly.
In short, a static controller would be a nightmare to work with.
You have for example controller "Home" and action "FillData",
and another controller "Student" and action "FillData".
Imagine what will happen if you make action "FillData" a static method, and could be called in any other controller easily.
It would be a big ISSUE.

ASP.NET MVC Controller Constructor Called Before Authentication

I have an ASP.NET MVC application with a controller that looks something like this:
[Authorize]
public class MyController : Controller
{
IMyRepository myRepository;
public MyController(IMyRepository myRepository)
{
this.myRepository = myRepository;
}
...
}
I have noticed that this constructor gets called prior to authenticating the user, so if you are visiting the page for the first time the constructor is called prior to redirecting you to the login screen. There are many problems with this, the login page loads slower, the site has greater exposure to DOS attacks, and I'm a little nervous about unauthenticated, unauthorized users being able to invoke code 'behind the walls' sort of speak.
I could check the incomming request in the constructor and bail unless the user is authorized, but I'm using IOC (Windsor) which makes that a bit tricky, my repository is going to be initialized regardless of whether or not I store the instance, so I'd be left checking authentication in each repository's constructor. Is there an easy way to get .NET MVC to authenticate the user prior to invoking the constructor? I'm thinking something like adding [PrincipalPermission(SecurityAction.Demand, Authenticated = true)] to the controller, but there might be a better way still.
EDIT:
Ok, not too happy about it, but the show must go on for now. I cannot delay initializing the repository until some later point in time from within the controller. When your controller uses IOC as in my example, you get an already instantiated implementation of your repository interface at the time that the controller is instantiated. If I had control over the repository being created, I could easily just call IsAuthenticated, no need for a new method. In order to take control of the repository initialization you would have to implement some sort of lazy/late initialization in the repository itself in each implementation. I do not like this solution because it adds needless complexity and more importantly coupling between the controller and repository. The repository implementation(s) may be used in other contexts where lazy initialization doesn't make sense IMHO.
The controller needs to be instantiated before authorization happens because it can act as its own authorization filter via the OnAuthorization method. Changing that behavior would involve replacing some core parts of the mvc pipeline. Is there a particular reason why you think the AuthorizedAttribute might not do its job?
Another option you could consider is initializing your repository in the OnActionExecuting of your controller method instead of in the constructor.
You can use HttpModules (or HttpHandler) to authenticate the request earlier in the pipeline.
MSDN: Introduction to HTTP Modules
MSDN: Implementing Intercepting Filter in ASP.NET Using HTTP Module
EDIT
With the introduction of OWIN you can configure the entire request pipeline middleware and put authorization at whatever stage you want. Same idea as above but a bit easier to implement.
Paul,
the instantiation of the controller is many many processes ahead of any actions on the controller being callable. even if the would be attacker attempted to benefit from this time lapse between instantiation and the login-screen, the controller action would only be able to run if the action had the authority to do so i.e. i'm assuming that your actions or controller all have the [Authorize] attribute on them.
I don't think you need worry too much about this and can rest easy, tho' i understand your obvious curiosity.
In terms of DOS attacks, it really should not matter -- after the first hit, which one sees alot when developing, the controller instantiation should be cheap. Well, unless you are DDOSing yourself by having the constructor do actual work such as pre-caching database lookups . . .

In ASP.NET MVC, why wouldn't I tack on HandleError on a base controller and be done with it?

Since HandleError is inherited by the derived Controllers, why wouldn't I just create (or have) a base controller, and apply HandleError on it so that any controllers that inherits from the base controller will automatically be handled as well?
And then I would tack on overriding HandleError on controllers and individual actions.
Can anyone think of any reason why I wouldn't want to apply HandleError to the base controller?
I know this question is old, but if you're now using MVC 3 I'd suggest using a global filter instead. See the Global Filters section of Scott Guthrie's post here
To me HandleError on a base controller is like surrounding your entire application with a try{} catch{} block. You've essentially stopped treating exceptions like exceptions made them a normal occurrence in your application.
You could only "catch" what you know may happen and not everything that may happen.

IAuthorizationFilter + Ninject2

I'm currently using Ninject2 to bind the various services and repositories in my MVC app. That part seems to be working just fine. Now I'd like to also bind my own class to IAuthorizationFilter and all actions that have the attribute set.
I've created a class that inherits from AuthorizationFilter and Implements IAuthorizationFilter.
I've also add this to my binding module:
Bind(Of IAuthorizationFilter).To(Of MyAuthFilter)
The last time I checked, the Ninject Mvc bits had support for also binding the 4 types of action filters.
Has anyone else done this? Whenever I run the site, the url that invokes the action marked Authorize just redirect to the login page, and never hits the breakpoint in my filter class.
If I were using a custom attribute, it would work, but changing all of the Authorize attributes defeats the purpose of using Ninject every time I want to swap one out of course.
It's not enough to register MVC filters with Ninject; you also have to tell MVC when to execute them. That's why you still need the custom attribute. The injection support in Ninject.Web.Mvc is to allow dependencies to be injected into filters.

Resources