Preventing AllowAnonymous - asp.net-mvc-4

I have a base controller which is globally marked as [Authorize]. Is there a way to prevent Controllers which inherit it from overriding the authorization requirement by simply adding the [AllowAnonymous] attribute?
Here is my exact scenario: I have three base controllers: one is for anonymous users, and two are for logged in users, both of which are globally decorated with [Authorize]. Each new controller that is created inherits from one of the base three, depending on which functionality is needed. One of the [Authorize] controllers contains "highly secure" functionality which absolutely should not be run by anonymous users. A developer inheriting from this "secure" base controller accidentally decorated some methods with [AllowAnonymous] which enabled anonymous users to potentially access the "secure" functionality in the base controller. It was caught in testing but I thought it would be a good idea to prevent that type of mistake, and I'm wondering if there is a simple way to do that. For now, I have taken all of the code inside of the secure base controller and wrapped it in blocks of:
if (Request.IsAuthenticated)
{
// do stuff
}
else
{
// redirect to login page, basically simulating what [Authorize] does
}
The above accomplishes what I want, however it kind of defeats the purpose of the global [Authorize] decoration in the first place. I'm envisioning something along the lines of:
[Authorize(AllowAnonymousOverride=false)] // this doesn't exist, but might be helpful
Is there a better way to accomplish this functionality?

The correct way to do this is to derive your own AuthorizeAttribute. The default AuthorizeAttribute looks like:
namespace System.Web.Mvc
{
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
public virtual void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
{
throw new InvalidOperationException(MvcResources.AuthorizeAttribute_CannotUseWithinChildActionCache);
}
// This is the Important part..
bool flag = filterContext.ActionDescriptor
.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor
.IsDefined(typeof(AllowAnonymousAttribute), true);
if (flag)
{
return;
}
if (this.AuthorizeCore(filterContext.HttpContext))
{
HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
cache.SetProxyMaxAge(new TimeSpan(0L));
cache.AddValidationCallback(
new HttpCacheValidateHandler(this.CacheValidateHandler), null);
return;
}
this.HandleUnauthorizedRequest(filterContext);
}
}
}
Derive your own:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public bool IsAllowAnonymousEnabled { get; set; }
public virtual void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (OutputCacheAttribute.IsChildActionCacheActive(filterContext))
{
throw new InvalidOperationException(MvcResources.AuthorizeAttribute_CannotUseWithinChildActionCache);
}
// This is the Important part..
bool flag = IsAllowAnonymousEnabled
&& (filterContext.ActionDescriptor
.IsDefined(typeof(AllowAnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor
.IsDefined(typeof(AllowAnonymousAttribute), true));
if (flag)
{
return;
}
if (this.AuthorizeCore(filterContext.HttpContext))
{
HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
cache.SetProxyMaxAge(new TimeSpan(0L));
cache.AddValidationCallback(
new HttpCacheValidateHandler(this.CacheValidateHandler), null);
return;
}
this.HandleUnauthorizedRequest(filterContext);
}
}
Usage:
[CustomAuthorizeAttribute(IsAllowAnonymousEnabled = false)]
public class MyController : Controller
{
[AllowAnonymous]
public ActionResult Index()
{
// This will still execute Authorization regardless of [AllowAnonymous]
return View();
}
}
You can't call base.OnAuthorization() because it will Allow AllowAnonymous.

First, you seem to have a controller with some methods and then your approach is to inherit it so that the same methods are exposed. I wonder what's the point of having two or more controllers that expose the same data. Was is the mistake of that developer or rather it is a custom routine in your approach?
Then, you expect to have an attribute that prevents other attributes but this is clearly not possible in the language nor in the mvc framework.
Third, someone wrote a controller without unit tests or maybe with tests but no one verified these tests so that the issue was caught during manual testing phase. This indicates that the issue is wider and not only restricted to inheritance - suppose your developer wrote a controller that doesn't inherit anything and still exposes some critical data because of allow anonymous mark. Then what? Even if you have a remedy for your original issue, it wouldn't be able to catch the new possible issue.
My advice would be to have a custom analyzer attached to the post build event that scans all possible controllers and makes a list of all anonymous and restricted actions and compares it to a previously generated list. If there is a change, then an alert is created and someone has to resolve the issue manually, either by approving newly created actions or rejecting changes because a bug has been introduced.

Related

Access to container of Simple Injector MVC views

In a Sitecore project I've integrated Simple Injector using this article
It uses sitecore pipelines and then uses a method in App_start
namespace BBC.App_Start
{
public class SimpleInjector : IPackage
{
public void RegisterServices(Container container)
{
GetContainer.RegisterServices(container);
container.Register(() => new SitecoreContext(), Lifestyle.Scoped);
container.Register(() => new Container(), Lifestyle.Singleton);
}
}
}
Simply I can inject container into controller constructor but can't have container in View files.
I tried to declare a static property in App-start and save container to it. but still I'm getting no registration type in Views
What is the best way to have container object in views?
As Stephen suggests in his comment, the literal answer to your question is "you shouldn't do that - because it's not really the way MVC and DI are supposed to work". The more detailed answer goes something like this:
The job of your view is to present data that it has been passed via the Model. Views should not really contain logic. Very simple stuff like "if flag is false, hide this block of mark-up" is ok, but the more complex code to work out what the value of the flag is shouldn't be in the view.
MVC tries to make our website code better by encouraging you to separate presentation (the View) from data (the Model) and logic (the Controller). This should make our code easier to work with - So if you have processing that needs doing, then it should really be happening when your controller method runs.
If your view requires some special data, best practice suggests it should work it out in the controller method and pass it to the view in the model. The code might look more like this:
public class MyModel
{
public string SpecialData { get; set; }
}
public class MyController : Controller
{
public ActionResult DoSomething()
{
// do whatever processing is needed
var somethingCalculate = resultFromYourOtherObject();
// do other stuff
var model = new MyModel() { SpecialData = somethingCalculated };
return View(model);
}
}
And then the View just needs to accept the MyModel class as its model, and render the SpecialData property - no logic required.
I think also it's considered a bad idea to have calls to fetch objects from your DI container spread about your codebase. For MVC apps, generally your DI container gets wired in to the process of creating a controller for a request when the app starts up. Rather than passing about a DI Container into your controllers, the DI framework extends the Controller-creation process, and the container isn't exposed outside of this. When the MVC runtime needs to create a controller, the controller-creation logic uses the DI framework to fetch objects for all the controller's dependencies.
Without more detail about what you actually want to achieve, it's difficult to say what the "right" approach to creating your object(s) here is, but the two most common patterns are probably:
1) Constructor injection: Your controller has a parameter which accepts the object required. The DI container creates this object for you at the point where it creates the controller, so your controller gets all its dependencies when it is created. Good for: scenarios where you know how to create the object at the beginning of the request.
public interface IMySpecialObject
{
string DoSomething();
}
public class MyController : Controller
{
private IMySpecialObject _specialObject;
public MyController(IMySpecialObject specialObject)
{
_specialObject = specialObject;
}
public ActionResult RenderAView()
{
// do some stuff
var data = _specialObject.DoSomething();
return View(data);
}
}
As long as IMySpecialObject and a concrete implementation for it are registered with your DI container when your app starts up, all is well.
2) Factory classes: Sometimes, however, the object in question might be optional, or it might require data that's not available at controller-creation time to create it. In that case, your DI framework could pass in a Factory object to your controller, and this is used to do the construction of the special object later.
public interface ISpecialFactory
{
ISpecialObject CreateSpecialObject(object data);
}
public class MyController : Controller
{
private IMySpecialFactory _specialFactory;
public MyController(IMySpecialFactory specialFactory)
{
_specialFactory = specialFactory;
}
public ActionResult RenderAView()
{
// do some stuff
if( requireSpecialObject )
{
var data = getSomeData();
var specialObject = _specialFactory.CreateSpecialObject(data);
var data = _specialObject.DoSomething();
return View(data);
}
return View("someOtherView");
}
}
But a good book on using DI may suggest other approaches that fit your specific problem better.

Injection of Request Scope objects into MVC ActionFilterAttribute

I have a shopping cart service IShoppingCartService that is defined with Ninject as being InRequestScope
this.Bind<IShoppingCartService>().To<ShoppingCartService>().InRequestScope();
It loads the user's shopping cart and caches it internally. Once the request is over then the service object goes away.
I needed to access the shopping cart within an ActionFilter so I used the [Inject] attribute.
public class MyActionFilterAttribute : ActionFilterAttribute
{
[Inject]
public IShoppingCartService ShoppingCartService
{
get; set;
}
}
I can then use it in the action filter like this
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var cart = ShoppingCartService.ShoppingCart;
...
}
Now for the weird part. This has been working just fine for a year or more - and then suddenly (after recently upgrading Ninject and MVC) I notice that the shopping cart is being cached (i.e. not InRequestScope).
On further research I see that ActionFilters are singletons (I verified this given that the constructor was only ever called once). So once an instance of the shopping cart is loaded it is locked in forever.
So my question is - how on earth did this ever work? Did something recently change in Ninject or MVC that could have allowed this to work before.
My fix right now is to do the following :
public IShoppingCartService ShoppingCartService
{
get
{
var scs = (IShoppingCartService) DependencyResolver.Current.GetService(typeof(IShoppingCartService));
return scs;
}
}
I'm really confused though as to how this ever could have worked - and it definitely did. What should I have done instead?
Maybe while the filter attribute was only instantiated once, the property was [Injected]-ed every time the page as hit. But let's look forward :)
In 2010 a "new" way was implemented in Ninject.MVCx (x =3, 5,..) on how to inject stuff into action filters. It doesn't need to rely on attributes and it supports constructor injection. Here's how it looks like:
(Fair warning: i don't usually do asp.net development and i didn't get to try out if the following does change anything about the lifecycle of the IActionFilter, so you'll have to try it out yourself. If you do, please provide feedback)
public class MyActionFilter : IActionFilter
{
private readonly IShoppingCartService shoppingCartService;
public MyActionFilter(IShoppingCartService shoppingCartService)
{
this.shoppingCartService = shoppingCartService;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var cart = ShoppingCartService.ShoppingCart;
...
}
}
The filter then needs to be bound by a special method BindFilter:
this.BindFilter<MyActionFilter>(FilterScope.Action, 0)
.WhenControllerTypeIs<YourController>();
which would apply it to all the actions of YourController.
There's also other targets you can apply the filter to, by using:
// Is applied to all actions of controllers which have the FooAttribute
this.BindFilter<MyActionFilter>(FilterScope.Action, 0)
.WhenControllerHas<FooAttribute>();
// Is applied to all actions which have the FooAttribute
this.BindFilter<MyActionFilter>(FilterScope.Action, 0)
.WhenActionHas<FooAttribute>();
// Is applied to all actions named Index
this.BindFilter<MyActionFilter>(FilterScope.Action, 0)
.When((controllerContext, actionDescriptor) =>
actionDescriptor.ActionName == "Index");
There's some more info on that which can be found in a great article by Remo Gloor: Official Ninject MVC extension gets support for MVC3 (chapter Dependency Injection for filters)

How can I kick the user if I change IsConfirmed column?

I use ASP.NET SimpleMembership..
My scenario;
The user login and then I change IsConfirmed column to false on webpages_Membership table..
And the user try to change page, the login page seems to the user..
Your most sensible options are to use any of the authentication related steps in Global.asax.cs, or to derive from AuthorizeAttribute. Given that non-confirmed users are going to have to get to somewhere (for example in order to confirm their account) then you probably don't want the former. With either approach their next request will get denied.
Therefore, I would just extend your [Authorize] attribute to do something like the following, and just use that in the appropriate Controllers and Actions instead of [Authorize] (I'm assuming C# as you didn't specify language in your tags):
public class AuthorizeIfConfirmedAttribute : AuthorizeAttribute {
protected override bool AuthorizeCore(HttpContextBase httpContext) {
if (!base.AuthorizeCore(httpContext)) return false;
System.Security.Principal.IIdentity user = httpContext.User.Identity;
return WebMatrix.WebData.WebSecurity.IsConfirmed(user.Name);
}
}
[AuthorizeIfConfirmed]
public class MyController { ... }
(If you want to use a custom property on your UserProfile class instead of IsConfirmed then you can simply adjust this code accordingly).
The advantage of this approach is that it keeps all your authorization logic in the usual place, and you can also combine it with role enforcement, e.g.:
[AuthorizeIfConfirmed(Roles = "admin")]
public class MyController { ... }
Note that if you use WebApi or SignalR you may have to include these checks in however you are performing request authorization for the apis as well.
I user Application_AuthenticateRequest in Global.asax.. Because my application needs authenticate on all pages..
protected void Application_AuthenticateRequest()
{
if (WebSecurity.IsAuthenticated)
{
bool isConfirmed = (..your codes here..)
if (isConfirmed == false)
{
WebSecurity.Logout();
}
}
}

MVC 4 How to process a url parameter on every page, base controller?

Looking for some guidance in designing my new MVC 4 app.
I would like to have a url parameter s=2011 on every page of the app to let me know what year of data I'm working with. Obviously, the user will have a way to change that parameter as needed.
I will need that parameter in every controller and wondering the best way to do this. I was thinking of creating a base controller that reads Request.QueryString and puts the year into a public property. However, considering all the extensability points in MVC, I'm wondering if there's a better way to do this?
This very much depends on the design of your app, but just to give you two alternatives
IActionFilter
If you are doing data context per request you can use a global IActionFilter to hook pre-action execution globally and apply a query filter to your data context behind the scenes.
Major down-side of this is that to test the controller you will need to have the full MVC pipeline setup so that the actionfilter gets applied properly.
Dependency Injection
Instead of using sub-classing (base controller as you say) you can use dependency injection . Keeping things more loose will allow you to pull the filter from query string, cookie, user setting in the database or whatever else - without your controller knowing where it comes from.
Here is some pseudo code how I would do it if I was using something like Entity Framework or Nhibernate (also I am sure applicable with other technologies as well)
public Car
{
public string Year { get; set; }
}
public class CarsDataContext : DbContext
{
private IQuerable<Cars> _cars = null;
private Func<Car, bool> _carsFilter = null;
public IQuerable<Car> Cars {
get {
if (_carsFitler != null)
return _cars.Where(_carsFitler);
return _cars;
}
set { _cars = value; }
}
public void ApplyCarsFilter(Func<Car, bool> predicate)
{
_carsFilter = predicate;
}
}
Assuming you have dependency injection setup already (NInject or whichever other framework) in you can configure how the context to be intialized
Bind<CarsDataContext>().ToMethod(() => {
string yearFilter = GetYearFilter(); // can be coming from anywhere
CarsDataContext dataContext = new CarsDataContext();
dataContext.Applyfilter(car => car.Year == yearFilter);
return dataContext;
}).InRequestScope();
Then my controller knows nothing about the data filtering and I can easily test it:
class MyController : Controller
{
public MyController(CarsDataContext dataContext)
{
}
...
}
However I would only do this is filtering the dataset was across many controllers and important part of my software. Otherwise it's pure over-engineering.

Authorize Attribute not filtering on DbDataController

I'm trying to use the new MVC4 DbDataController to expose a restful data api.
My problem is trying to secure this. I have created custom authorization attributes that derive from Authorize Attribute
public class AdminOnlyAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!IsAllowed()) {
filterContext.Result = new HttpUnauthorizedResult("Not logged in");
}
...
}
And that works fine when applied to my normal controller actions. I'm trying to use the same thing in my data service like this:
[AdminOnlyAttribute]
public class DataServiceController : DbDataController<AppBuilderDataContext>
{
[AdminOnlyAttribute]
public IQueryable<Thing> GetThings()
{
return DbContext.AllMyThings();
}
}
You can see I've tried my attribute on both the controller and the action, but it's not firing for either one. I've set a breakpoint inside my authorize attribute function, and it's not getting called.
I'm pretty sure Scott Guthrie said this was going to work. Am I doing it wrong, or do I need a completely different method to secure these?
To work with an DataController or any other type derived from ApiController your attribute must derive from System.Web.Http.AuthorizeAttribute