【问题标题】:Authenticated user is lost in web api owin middleware经过身份验证的用户在 web api owin 中间件中丢失
【发布时间】:2021-09-12 07:53:24
【问题描述】:

我正在使用owin middlewareJwt Bearer Aurhentication 以及Autofac 来帮助我的Webapi 处理请求。

JwtBearerAuthentication 中间件工作正常并将 HttpContext.Current.User.Identity.IsAuthenticated 设置为 true 并且它会一直持续到管道到达 webapi middleware ,在我的 webapi 中,经过身份验证的用户丢失了

中间件顺序如下:

public void Configuration(IAppBuilder app)
{

    var config = new HttpConfiguration();
    WebApiConfig.Register(config);
    #region Autofac config

    var container = AutofacWebapiConfig.Initialize(GlobalConfiguration.Configuration);
    config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

    #endregion
    #region RoutConfig

    RouteConfig.RegisterRoutes(RouteTable.Routes);

    #endregion

    //Register middlewares
    app.UseAutofacMiddleware(container);
    app.UseAutofacWebApi(config);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
    app.UseJwtBearerAuthentication(new MyJwtAuthenticationOptions());
    app.Use<RedirectUnAuthenticateRequestsMiddleware>();
    app.Use<ReadBodyMiddleware>();
    app.UseWebApi(config); //in this middleware authenticated user is lost

}

这是我的 WebApiConfig 类:

    public static void Register(HttpConfiguration config)
    {
        // Owin auth
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter("Signature"));
        GlobalConfiguration.Configuration.IncludeErrorDetailPolicy =
IncludeErrorDetailPolicy.Always;
        // Web API routes
        config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
        config.MapHttpAttributeRoutes();
        config.Services.Insert(typeof(ModelBinderProvider), 0,
         new SimpleModelBinderProvider(typeof(DocumentModel), new FromFormDataBinding()));
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

你有什么想法吗?

Update:

在身份验证中间件后的我的 owin 中间件中,IsAuthenticated 设置为 true

  public override async Task Invoke(IOwinContext context)
{
      var isAuth=context.Request.User.Identity.IsAuthenticated;//It is true as expected.
                await Next.Invoke(context);
                return;
}

但是当它到达我的控制器时

HttpContext.Current.User.Identity.IsAuthenticated;//It is false.

【问题讨论】:

    标签: c# asp.net-web-api jwt autofac owin-middleware


    【解决方案1】:

    问题出在WebApiConfig 类中的这一行;

    config.SuppressDefaultHostAuthentication();
    

    当我发表评论时,问题消失了,经过身份验证的用户仍然存在于 webapi 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-11
      • 1970-01-01
      • 2015-01-30
      • 1970-01-01
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      相关资源
      最近更新 更多