Reputation: 2442
I'm ripping my hair out. I am successfully creating a bearer token during a login. When I pass that token to my Authorized api controller everything works as expected.
If I do not pass a token or pass an invalid token I get this error message:
An error occurred when trying to create a controller of type 'AccountsController'. Make sure that the controller has a parameterless public constructor."
I am injecting objects into my controller so I do not have a parameterless constructor. Regardless, shouldn't an unauthorized response be sent back?
Here is my setup for OWIN:
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = new OauthServerProvider()
};
// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
Thanks, Paul
Upvotes: 0
Views: 1073
Reputation: 4763
The default ASP.NET mechanism that builds controllers expects a parameterless constructor unless you use an IoC container and explicitly define how the controller should resolve dependencies.
The easy way to fix this is creating a parameterless constructor and call the constructor with parameters like this:
public TaskController()
: this(new TaskService(new TaskRepository()))
{
}
public TaskController(ITaskService taskService)
{
this.taskService = taskService;
}
The problem here is that your DI is not useful anymore. You have to configure your DI in the Startup class.
I show you an example in Castle Windsor:
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
config.Filters.Add(new WebApiAuthorizeAttribute());
...
// Dependency Resolver
var container = new WindsorContainer().Install(new WebApiControllersInstaller());
var httpDependencyResolver = new WindsorDependencyResolver(container);
config.DependencyResolver = httpDependencyResolver;
//Uncomment next lines for Composition Root DI configuration intead of Dependency Resolver
//var container = new WindsorContainer().Install(new WebApiControllersInstaller());
//config.Services.Replace(typeof(IHttpControllerActivator), new WindsorCompositionRoot(container));
}
Upvotes: 1