0
votes

I have a project where I use MVC5 with WebAPI. Authentication uses Owin. I want to setup Ninject dependency resolver. I tried soultions for MVC5, for MVC5 with Owin, for WebApi for WebAPI with Owin. But I can't combine them. Does anybody have the steps for MVC5+WebApi+Owin+Ninject bundle?

One of the last solution to make it workable for WebApi I followed here: https://github.com/ninject/Ninject.Web.Common/wiki/Setting-up-a-OWIN-WebApi-application

I added latest NuGet packages. My Startup class:

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var webApiConfiguration = new HttpConfiguration();
        WebApiConfig.Register(webApiConfiguration);
   app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(webApiConfiguration);
        ConfigureAuth(app);
    }

    private static StandardKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        return kernel;
    }
}

WebApiConfig. I didn't add any routing configurations. As it is added in Global.asax:

 public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var webApiConfiguration = new HttpConfiguration();
        app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(webApiConfiguration);
        ConfigureAuth(app);
    }

    private static StandardKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        return kernel;
    }
}

WebApi with routings(and removed routing registration in Global.asax) it doesn't work too. On each request to ANY WebApi I have "{"Message":"Authorization has been denied for this request."}":

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var webApiConfiguration = new HttpConfiguration();
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        webApiConfiguration.SuppressDefaultHostAuthentication();
        webApiConfiguration.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        webApiConfiguration.MapHttpAttributeRoutes();
        webApiConfiguration.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
        app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(webApiConfiguration);
        ConfigureAuth(app);
    }

    private static StandardKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        return kernel;
    }
}

ConfigureOAuth. I'm using two way authentication one based on cookie another based on Tokne. One suitable for WebApi another for MVC:

public void ConfigureAuth(IAppBuilder app)
    {

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Login"),
            Provider = new CookieAuthenticationProvider
            {
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<UserManager, User>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager,DefaultAuthenticationTypes.ApplicationCookie))
            }
        });

        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = true
        };
    }

And my API controller.

[Authorize(Roles = "Admin")]
public class AdminPanelController : ApiController
{
    private readonly IAdminPanelService _service;
    public AdminPanelController(IAdminPanelService service)
    {
        _service = service;
    }
}

I always have exception that AdminPanelController should be parameterless. If I add any routing to WebApiConfig I will have the same exception for AdminPanelController and not authorized for other(though Bearer Token generates and pass to WebApi controllers)

1
I have this setup, and it does work. When you say you can't combine them, which part is not working? What do you have so far? - ngm
@ngm. I updated my message. Could you please review it. - Archon

1 Answers

0
votes

To get Dependency Injection to work with Web API you should implemented an IDependencyResolver for Ninject and apply it to HttpConfiguration.DependencyResolver.

See more here. You can even find a NuGet package here.