Implement FluentSecurity 2.0.0 with Ninject MVC - asp.net-mvc-4

Error activating ISecurityContext using binding from ISecurityContext to SecurityContext.
I'm getting the above error with FluentSecurity 2.0.0 when I'm trying to configure it with Ninject.Web.Mvc3 in an ASP.NET MVC 4 web application.
I think the internal IoC of FluentSecurity and the Ninject IoC may be clashing. Or I may be incorrectly setting up the DependencyResolver in the SecurityConfigurator.
I need to set it up with IoC as I need to get the UserRoles through an injected class.
public static class SecurityConfig
{
public static ISecurityConfiguration Configure()
{
SecurityConfigurator.Configure(
configuration =>
{
configuration.ResolveServicesUsing(
DependencyResolver.Current.GetServices,
DependencyResolver.Current.GetService);
configuration.DefaultPolicyViolationHandlerIs(() => new DefaultPolicyViolationHandler());
configuration.GetAuthenticationStatusFrom(
() => HttpContext.Current.User.Identity.IsAuthenticated);
configuration.GetRolesFrom(
() =>
((IPersonManager)DependencyResolver
.Current
.GetService(typeof(IPersonManager)))
.GetCurrentUserRoles());
configuration.ForAllControllers().DenyAnonymousAccess();
configuration.For<AdminController>().RequireAnyRole(Role.Administrator);
});
return SecurityConfiguration.Current;
}
}
Where am I going wrong? Is there another way I could achieve this?

I faced the same situation. It happened because Ninject throws an exception when cannot resolve a dependency. I solved it implementing my own ISecurityServiceLocator
public class FluentSecurityServiceLocator : ISecurityServiceLocator
{
public static IKernel Kernel { get; set; }
public object Resolve(Type typeToResolve)
{
return Kernel.TryGet(typeToResolve);
}
public IEnumerable<object> ResolveAll(Type typeToResolve)
{
if (!Kernel.GetBindings(typeToResolve).Any())
{
return new List<object>();
}
return Kernel.GetAll(typeToResolve);
}
}
I passed the kernel instance in my ninject configuration class
FluentSecurityServiceLocator.Kernel = kernel;
Hope this helps!

I'm not really familiar with Ninject but are you sure that DependencyResolver.Current.GetServices and DependencyResolver.Current.GetService won't throw an exception when FluentSecurity asks for something (like ISecurityContext) that is not registered with Ninject?
In structuremap there is a method called TryGetInstance that won't throw an exception when asking for something that is not registered in the container. You can read more on how FluentSecurity and IoC works here:
https://github.com/kristofferahl/FluentSecurity/wiki/IoC-container-integration

Related

ASP.NET 5 Controller dependency injection of concrete class with no interface in to controller

Is it possible to use StructureMap to scan assemblies to be aware of concrete classes that do not implement interfaces? I am fairly new to StructureMap so not sure if this should be an obvious thing.
For context, below are the highlights of the classes I am working with. UserController depends on an instance of UserManager which depends on an instance of IUserRepository.
public interface IUserRepository { }
public class UserRepository { }
public class UserManager
{
public UserManager(IUserRepository repository) { }
}
public class UserController
{
public UserController(UserManager manager) { }
}
This is the code I have in my Startup.ConfigureServices method to do the scanning for DI:
// Setup dependencies using StructureMap
var container = new Container(x =>
{
x.Scan(s =>
{
s.AssemblyContainingType<UserRepository>();
s.WithDefaultConventions();
});
});
container.Populate(services);
The problem is I get the following error:
Unable to resolve service for type 'UserManager' while attempting to
activate 'UserController'.
If I add the following line to Startup.ConfigureServices then it works, but I am looking for a solution that doesn't require me to have a line for every manager. I have been thinking StructureMap assembly scanning could solve this but I am open to other solutions as well.
services.AddTransient<UserManager>();
Add .AddControllersAsServices() extention method to your services.AddMvc() call.
Result:
services.AddMvc().AddControllersAsServices();

Using one Dependency Resolver for SignalR and standard MVC controllers?

Currently I am using Unity 3.x as my IoC. I also using the Unity.MVC4 library to help manage the lifetime of my resolver. Here is what my resolver looks like:
namespace Wfm.Core.Common.Mvc.Unity
{
public class WfmDependencyResolver : UnityDependencyResolver
{
public WfmDependencyResolver(IUnityContainer container) : base(container)
{
}
private static WfmDependencyResolver _wfmGrabbrResolver;
public static WfmDependencyResolver Instance { get { return _wfmGrabbrResolver ?? (_wfmGrabbrResolver = new WfmDependencyResolver(InstanceLocator.Instance.Container)); } }
}
}
The UnityDependencyResolver comes from the Unity.MVC4 library. In my Globabl.asax.cs file I am setting the resolver like this:
DependencyResolver.SetResolver(WfmDependencyResolver.Instance);
Here is my singleton InstanceLocator class:
public class InstanceLocator
{
private static InstanceLocator _instance;
public IUnityContainer Container { get; private set; }
private InstanceLocator()
{
Container = new UnityContainer();
}
public static InstanceLocator Instance
{
get { return _instance ?? (_instance = new InstanceLocator()); }
}
public T Resolve<T>()
{
try
{
return WfmDependencyResolver.Instance.GetService<T>();
}
catch(Exception ex)
{
return default(T);
}
}
public T ResolvewithoutManager<T>()
{
try
{
return Container.Resolve<T>();
}
catch (Exception)
{
throw;
}
}
}
This obviously works well from my MVC controllers, but what would be a good solution to allow my application to resolve inside my Hub controllers along with my MVC controllers. Currently, I created a singleton class that allows me to resolve my types manually. I can specifically resolve my types inside my Hubs using my the class like this:
InstanceLocator.Instance.Resolve<ISomeInterface>();
While this works, its not ideal from a development standpoint. Reason being, I want my types to be injected and not manually instantiated. My hubs and Controllers are inside the same MVC application and I do not want to have separate them right now.
There's an entire article devoted to dependency injection in SignalR: http://www.asp.net/signalr/overview/extensibility/dependency-injection
So all you have to do is write a custom dependency resolver for SignalR which obviously will be a simple wrapper to your commonly shared Unity container.

FluentSecurity and Ninject

Error activating IntPtr
I'm trying to configure FluentSecurity (v.1.4) with Ninject (v.3) in an ASP.NET MVC 4 application.
I can't set up the ResolveServicesUsing() configuration expression without throwing the above error.
SecurityConfigurator.Configure(
configuration =>
{
configuration.ResolveServicesUsing(
DependencyResolver.Current.GetServices,
DependencyResolver.Current.GetService);
...
I've also tried using another overload for ResolveServicesUsing()
configuration.ResolveServicesUsing(
type => DependencyResolver.Current.GetServices(type));
FluentSecurity needs to be configured with Ninject to inject the method for finding my users' roles and also for the PolicyViolationHandler implementations.
UPDATE
I've found I can leave out the offending lines and still have my GetRolesFrom() implementation called (hurrah):
configuration.GetRolesFrom(
() =>
((IPersonManager)DependencyResolver
.Current
.GetService(typeof(IPersonManager)))
.GetCurrentUserRoles());
I still can't get my PolicyViolationHandler to work, however:
public class RequireRolePolicyViolationHandler : IPolicyViolationHandler
{
public ActionResult Handle(PolicyViolationException exception)
{
return new RedirectToRouteResult(
new RouteValueDictionary(
new
{
action = "AccessDenied",
controller = "Home"
}));
}
}
I'm doing the binding in a NinjectModule like this:
public class SecurityModule : NinjectModule
{
public override void Load()
{
this.Kernel.Bind<IPolicyViolationHandler>()
.To<RequireRolePolicyViolationHandler>();
}
}
Error activating IntPtr
Unfortunately you havn't posted the complete StackTrace. But usually you will get this exception when injecting a Func to some class without having a binding or using the Factory extension.
I use Fluent Security with Ninject as IOC container.
In your Fluent Security configuration, you need to set the service locator to the NinjectServiceLocator.
public static void Configure(IKernel kernel)
{
var locator = new NinjectServiceLocator(kernel);
ServiceLocator.SetLocatorProvider(() => locator);
SecurityConfigurator.Configure(
configuration =>
{
configuration.GetAuthenticationStatusFrom(() => HttpContext.Current.User.Identity.IsAuthenticated);
....
}
You can get the locator here.
Hope this helps

Setting IBus Property in MVC Filter

I'm trying to send a command from a filter in my MVC4 project to my command processor.
The problem:
I can't get an NServiceBus instance in the filter to fill.
The components:
ASP.NET MVC 4
NServiceBus version 3
StructureMap
The Attribute/Filter:
namespace AMS.WebApp.Filters
{
public class AMSAuthorizeAttribute : AuthorizeAttribute
{
public IBus Bus { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool accessGranted = false;
accessGranted = base.AuthorizeCore(httpContext);
// arbitrary command, don't worry about it
// Why is Bus still null?
var requestAccess = new RequestingAccess();
Bus.Send("AMS.AccessControl.CommandProcessor", requestAccess);
//if(isAdmin)
// accessGranted = true;
#if DEBUG
accessGranted = true;
#endif
return accessGranted;
}
}
}
The IOC Code:
using AMS.WebApp.Filters;
using NServiceBus;
using StructureMap;
namespace AMS.WebApp.DependencyResolution {
public static class IoC {
public static IContainer Initialize() {
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
scan.AssembliesFromApplicationBaseDirectory();
scan.WithDefaultConventions();
});
//This doesn't work
//x.SetAllProperties(y => y.OfType<IBus>());
//Neither does this
//x.ForConcreteType<AMSAuthorizeAttribute>()
// .Configure
// .Setter<IBus>(a => a.Bus)
// .IsTheDefault();
});
return ObjectFactory.Container;
}
}
}
Also, my attempt to bypass structuremap completely by passing in the bus instance from the controller resulted in:
An object reference is required for the non-static field, method, or property
At this point I'm pretty sure its something awkward with attributes/filters and structuremap, but I'm not really sure what that is.
WARNING: the accepted answer does not fix the actual problem of getting nservicebus in an action filter, but it does address how to get DI in an action filter. See ASP.NET MVC4 NServiceBus Attribute/Filter StructureMap for the Nservicebus specific question
Take a look at this post. I think this is what you're looking for.
http://lostechies.com/jimmybogard/2010/05/03/dependency-injection-in-asp-net-mvc-filters/
Edit:
I think you have two different issues here.
Using DI on a filter
Configuring DI on NServiceBus
Can you please post your code which initializes NServiceBus for StructureMap?
You are looking for somthing like this:
Configure.With().StructureMapBuilder()

Ninject property binding, how to do correctly

I have installed Ninject (v4.0.30319) package in test project to test. Create test code below, unfortunately ValidateAbuse.Instance.Repository is always Null. Why Ninject do not bind repository to ValidateAbuse.Repository property?
Some of you may suggest to use constructor binding but I can't use it due to code structure. The below code is just example and I need to find a way to bind to property.
Test method which always fail
[TestMethod]
public void PropertyInjection()
{
using (IKernel kernel = new StandardKernel())
{
kernel.Bind<ISettingsRepository>().To<SettingsRepository>();
Assert.IsNotNull(ValidateAbuse.Instance.Repository);
}
}
The repository interface
public interface ISettingsRepository
{
List<string> GetIpAbuseList();
List<string> GetSourceAbuseList();
}
The repository implementation
public class SettingsRepository : ISettingsRepository
{
public List<string> GetIpAbuseList()
{
return DataAccess.Instance.Abuses.Where(p => p.TypeId == 1).Select(p => p.Source).ToList();
}
public List<string> GetSourceAbuseList()
{
return DataAccess.Instance.Abuses.Where(p => p.TypeId == 2).Select(p => p.Source).ToList();
}
}
The class to which I am trying to bind repository
public class ValidateAbuse
{
[Inject]
public ISettingsRepository Repository { get; set; }
public static ValidateAbuse Instance = new ValidateAbuse();
}
Ninject will only bind properties on an object when it creates an instance of that object. Since you are creating the instance of ValidateAbuse rather than Ninject creating it, it won't know anything about it and therefore be unable to set the property values upon creation.
EDIT:
You should remove the static singleton from ValidateAbuse and allow Ninject to manage it as a singleton.
kernel.Bind<ValidateAbuse>().ToSelf().InSingletonScope();
Then when you ask Ninject to create any class that needs an instance of ValidateAbuse, it will always get the same instance.
It seems like you don't fully understand how Ninject works or how to implement it so I would suggest you read the wiki https://github.com/ninject/ninject/wiki/How-Injection-Works and follow some more basic examples before trying to wire it into an existing application.