【问题标题】:WebApi2 - No OWIN authentication manager is associated with the requestWebApi2 - 没有 OWIN 身份验证管理器与请求关联
【发布时间】:2017-03-13 12:26:19
【问题描述】:

我正在构建一个带有承载令牌身份验证的 Web API 2 项目。

access_token 的请求有效,但我的其他方法无效。 API 正在返回以下内容:

没有与请求关联的 OWIN 身份验证管理器

完整回复消息

{  
   "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);
    }
}

我搜索了这个错误,发现有人说它是通过以下方式解决的:

  1. Webconfig:设置&lt;modules runAllManagedModulesForAllRequests="true"&gt;
  2. 安装 Microsoft.Owin.Host.SystemWeb
  3. 检查我是否使用Context.GetOwinContext() 而不是Request.GetOwinContext()

Webconfig 选项不起作用。

我有 Host.SystemWeb 包。

而且我没有在任何地方调用 GetOwinContext。

有什么想法吗?

谢谢。

【问题讨论】:

    标签: c# asp.net asp.net-web-api2 owin


    【解决方案1】:

    正如异常所说,身份验证管理器丢失了。 为了解决这个问题,我会尝试在 Startup.cs 类中重新配置不记名令牌配置。

    试试这个方法

    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());
    } 
    

    更新

    所以问题似乎在于 SupressDefaultHostAuthentication。 如果您没有在主机中运行,则无需添加 SupressDefaultHostAuthentication ,因此请在 WebApiConfig 中删除它(有关更多信息,请参阅此答案的 cmets)。 Here's 一篇关于该主题的好博文,可以更好地融入课堂。

    【讨论】:

    • 感谢您的回复。但是,返回相同的错误。这很奇怪,因为在另一个项目中我使用相同的配置并且它可以工作。我会查看 DLL 并尝试找出任何区别。
    • @LeandroSoares 好的。那么就很清楚了。您能否删除您在 webapiconfig 类中添加的 SuppressDefaultHostAuthentication 和 auth 过滤器并尝试?
    • 我已经尝试过这样做,它可以这样工作,但是它没有授权调用。
    • @LeandroSoares 因此,如果您将 [AllowAnonymous] 添加到控制器方法,请使用在该控制器的标头中添加的不记名令牌发出请求,并检查当前的上下文原则用户。那个用户是空的吗?
    • 不,用户不是空的,但一切都是空的
    【解决方案2】:

    当我将使用 MVC 5 的 Web API 2 模板构建的网站发布到实时 IIS 服务器时,我遇到了这个问题。它在 Visual Studio 的 IIS Express 上本地运行良好,但在完整的 IIS 服务器上给了我 No OWIN authentication manager is associated with the request 错误。

    我的解决方案是在 web.config 中进行这些更改:

    添加这个键(我从this answer学到的):

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

    并将&lt;modules&gt; 更改为&lt;modules runAllManagedModulesForAllRequests="true"&gt;,这是我从this answer 学到的。

    【讨论】:

      【解决方案3】:

      在位于 App_Start 文件夹中的脚手架 WebApiConfig.cs 文件中,您需要删除或注释掉以下行:

      //config.SuppressDefaultHostAuthentication();
      //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
      

      【讨论】:

        猜你喜欢
        • 2014-02-01
        • 1970-01-01
        • 2014-11-14
        • 2014-10-22
        • 2016-10-02
        • 2015-10-09
        • 2019-10-19
        • 2016-03-24
        • 2015-09-23
        相关资源
        最近更新 更多