4

I'm building an Web API 2 project with Bearer Token Authentication.

The request for the access_token is working but not my other methods. API is returning the following:

No OWIN authentication manager is associated with the request

Full Response Message

{  
   "Message":"An error has occurred.",
   "ExceptionMessage":"No OWIN authentication manager is associated with the request.",
   "ExceptionType":"System.InvalidOperationException",
   "StackTrace":"   at System.Web.Http.Owin.PassiveAuthenticationMessageHandler.SuppressDefaultAuthenticationChallenges(HttpRequestMessage request)\r\n   at System.Web.Http.Owin.PassiveAuthenticationMessageHandler.<SendAsync>d__0.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()"
}

Startup.cs

public partial class Startup
{
    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }
    static string PublicClientKey = "XXX";

    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseCors(CorsOptions.AllowAll);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientKey),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
            AllowInsecureHttp = true
        };

        app.UseOAuthBearerTokens(OAuthOptions);
    }
}

WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "ControllerAndAction",
        routeTemplate: "api/{controller}/{action}/{id}",
         defaults: new { id = RouteParameter.Optional }
    );
}

Global.asax

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }
}

I searched for this error and found some people who said that it was resolved by the following:

  1. Webconfig: Set <modules runAllManagedModulesForAllRequests="true">
  2. Installing Microsoft.Owin.Host.SystemWeb
  3. Check if I was using Context.GetOwinContext() instead of Request.GetOwinContext()

Webconfig options didn't work.

I had the Host.SystemWeb package.

And I didn't call GetOwinContext anywhere.

Any idea?

Thank you.

Leandro Soares
  • 2,902
  • 2
  • 27
  • 39

3 Answers3

6

As the exception tells, the authentication manager is missing. To fix this I would try to reconfigured the bearer token config in the Startup.cs class.

Try it this way

public void ConfigureAuth(IAppBuilder app)
{
    app.UseCors(CorsOptions.AllowAll);

    //You don't need these lines if you are using bearer token as the token is 
    //passed in the request header and not in the cookie
    //app.UseCookieAuthentication(new CookieAuthenticationOptions());
    //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

    OAuthOptions = new OAuthAuthorizationServerOptions
    {
        TokenEndpointPath = new PathString("/Token"),
        Provider = new ApplicationOAuthProvider(PublicClientKey),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
        AllowInsecureHttp = true
    };

    //Remove this part
    //app.UseOAuthBearerTokens(OAuthOptions);

    //And try to manually define the authorization server 
    //and the middleware to handle the tokens
    app.UseOAuthAuthorizationServer(OAuthOptions);
    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
} 

UPDATE

So the problems seemed to lay with the SupressDefaultHostAuthentication. If your not running in a host then there's no need to add the SupressDefaultHostAuthentication so remove that in the WebApiConfig (See comments to this answer for more info). Here's a good blog post on the topic which gives better insite of the class.

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
  • Thank you for your response. However, the same error is returned. It's strange because on another project I'm using the same configurations and It works. I'll look at the DLL's and try to catch any difference. – Leandro Soares Mar 13 '17 at 14:47
  • @LeandroSoares Ok. Then that's clear. Could you remove the SuppressDefaultHostAuthentication and the auth filter you're adding in the webapiconfig class and try? – Marcus Höglund Mar 13 '17 at 15:00
  • I already tried to do that, it works that way, however it doesn't authorize the calls. – Leandro Soares Mar 13 '17 at 15:04
  • @LeandroSoares So if you add [AllowAnonymous] to the controller method, make a request with the bearer token added in the header to that controller and check the current conext principle user. Is that user null? – Marcus Höglund Mar 13 '17 at 15:06
  • No the user is not null, but everything is empty – Leandro Soares Mar 13 '17 at 15:11
  • @LeandroSoares If the user is not null then you can add the [Authorize] attribute and it works. If you want to add more details to the principle, like role, email etc then you need to add claims in the token generator. – Marcus Höglund Mar 13 '17 at 15:13
  • What the hell? Why don't I need to add the SupressDefaultHostAuthentication? In my other project I use it and it works just fine – Leandro Soares Mar 13 '17 at 15:18
  • Ok, great that it works. If your not running in a host then there's no need to add the SupressDefaultHostAuthentication. Here's a good blog post on the topic https://brockallen.com/2013/10/27/host-authentication-and-web-api-with-owin-and-active-vs-passive-authentication-middleware/ – Marcus Höglund Mar 13 '17 at 15:39
  • Thank you very much, can you change your answer so I accept it? – Leandro Soares Mar 13 '17 at 15:54
  • this solutions is not working for .Net Framework , it does just for .Net Core i think. any idea how to make it in .Net Framework 4.5 MVC – Abdessamad Jadid Oct 14 '20 at 18:09
  • @AbdessamadJadid this solution is working for owin pipeline running on .net – Marcus Höglund Oct 17 '20 at 10:33
0

I had this issue when I published a website built using MVC 5's web API 2 template with Individual User authentication to a live IIS server. It worked fine locally on Visual Studio's IIS Express but gave me the No OWIN authentication manager is associated with the request error on a full IIS server.

The solution in my case was to make these changes in web.config:

Add this key (which I learnt from this answer):

  <appSettings>
    <add key="owin:AppStartup" value="[MyStartUpAssemblyNamespace].Startup, [MyAssemblyName]" />
    ...
  </appSettings>

And Change <modules> to <modules runAllManagedModulesForAllRequests="true"> which I learnt from this answer.

Community
  • 1
  • 1
tomRedox
  • 28,092
  • 24
  • 117
  • 154
0

In the scaffolded WebApiConfig.cs file, located in the App_Start folder, you need to remove or comment out the following lines:

//config.SuppressDefaultHostAuthentication();
//config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
Dharman
  • 30,962
  • 25
  • 85
  • 135