I get "Authorization has been denied for this request." error message when using OWIN oAuth middleware (with separate Auth and Resource Server)

I just came across the same problem and found the solution:

You need to register the OAuth Token Generator and OAuth Token Consumer things before WebAPI is registered.

Kind of makes sense if you think of this as a pipeline, where Authentication/Authorization should come before any request handling by the controllers.

TL;DR: Change

appBuilder.UseWebApi(config);

this.ConfigureOAuthTokenGenerator(appBuilder);
this.ConfigureOAuthConsumer(appBuilder);

To

this.ConfigureOAuthTokenGenerator(appBuilder);
this.ConfigureOAuthConsumer(appBuilder);

appBuilder.UseWebApi(config);

I was also receiving the error message 'Authorization has been denied for this request', although I don't have separate auth and resource servers.

I am using Ninject's OwinHost and had it configured in Startup before configuring OAuth, as follows:

public void Configuration(IAppBuilder app)
{
    var config = new HttpConfiguration();

    app.UseNinjectMiddleware(() =>
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        return kernel;
    }).UseNinjectWebApi(config);

    ConfigureOAuth(app);

    WebApiConfig.Register(config);
    app.UseCors(CorsOptions.AllowAll);
    app.UseWebApi(config);
}

I found that moving the Ninject configuration to the end resolved the problem, like so:

public void Configuration(IAppBuilder app)
{
    var config = new HttpConfiguration();

    ConfigureOAuth(app);

    WebApiConfig.Register(config);
    app.UseCors(CorsOptions.AllowAll);
    app.UseWebApi(config);

    app.UseNinjectMiddleware(() =>
    {
        var kernel = new StandardKernel();
        kernel.Load(Assembly.GetExecutingAssembly());
        return kernel;
    }).UseNinjectWebApi(config);
}

Maybe your problem is to do with the startup order of your middleware.


In my post I was clear that you need to override the machineKey node for both APIs (Authorization Server and Resource Server) and share the same machineKey between both web.config files. How do you host those 2 different projects? they are on the same machine or different machines? Please go back to step 5 from the post and check how you can achieve this.