c# - 用户 (IPrincipal) 在使用 Web Api 2.1 和 Owin 的 ApiController 构造函数上不可用

标签 c# owin asp.net-web-api2 katana asp.net-identity-2

我将 Web Api 2.1 与 Asp.Net Identity 2 一起使用。我试图在我的 ApiController 的构造函数上获取经过身份验证的用户(我正在使用 AutoFac 注入(inject)我的依赖项),但是当构造函数是打电话。

我正在尝试获取用户,以便为任何数据库写入操作生成审计信息。

我正在做的一些事情可以帮助诊断:
我正在使用 app.UseOAuthBearerTokens 作为Asp.Net Identity 2 的身份验证。这意味着我删除了app.UseCookieAuthentication(new CookieAuthenticationOptions( )) 当您使用 Asp.Net Identity 2 创建新的 Web Api 2.1 项目时默认启用。

WebApiConfig 中,我正在注入(inject)我的存储库:

builder.RegisterType<ValueRepository>().As<IValueRepository>().InstancePerRequest();

这是我的 Controller :

[RoutePrefix("api/values")]
public class ValuesController : ApiController
{
    private IValueRepository valueRepository;

    public ValuesController(IValueRepository repo)
    {
        valueRepository = repo;
        // I would need the User information here to pass it to my repository
        // something like this:
        valueRepository.SetUser(User);
    }

    protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
    {
        base.Initialize(controllerContext);

        // User is not avaliable here either...
    }
}

但是如果我在构造函数中检查 User 对象,这就是我得到的: User

身份验证有效,如果我不传递我的 token ,它将以 Unauthorized 响应。如果我传递 token 并尝试从任何方法访问用户,则它已通过身份验证并正确填充。它只是在调用时不会出现在构造函数中。

在我的 WebApiConfig 中,我正在使用:

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

    // Web API routes
    config.MapHttpAttributeRoutes();

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

     // ... other unrelated injections using AutoFac
 } 

我注意到,如果我删除以下行:config.SuppressDefaultHostAuthentication(),用户将填充到构造函数中。

这是预期的吗?如何在构造函数上获得经过身份验证的用户?

编辑: 正如 Rikard 所建议的,我尝试在 Initialize 方法中获取用户,但它仍然不可用,给我提供了与图片中描述的相同的东西。

最佳答案

问题确实在于 config.SuppressDefaultHostAuthentication()

This article by Brock Allen很好地解释了为什么会这样。该方法有意将主体设置为 null,以便像 cookie 这样的默认身份验证不起作用。相反,Web API Authentication filter然后负责身份验证部分。

当您没有 cookie 身份验证时删除此配置可能是一种选择。

一个简洁的解决方案 as mentioned here , 是应用程序的 Web API 部分的范围,以便您可以将此配置分离到特定路径:

public void Configuration(IAppBuilder app)
{
    var configuration = WebApiConfiguration.HttpConfiguration;
    app.Map("/api", inner =>
    {
        inner.SuppressDefaultHostAuthentication();
        // ...
        inner.UseWebApi(configuration);
    });
}

关于c# - 用户 (IPrincipal) 在使用 Web Api 2.1 和 Owin 的 ApiController 构造函数上不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23785528/

相关文章:

asp.net-mvc - 我如何在服务器端存储不记名 token 以及验证如何在 Web API 2 中注销时删除?

c# - SSIS-PostAsJsonAsync 不起作用

c# - 具有相同 URL 路由但不同 HTTP 方法的多个 Controller

c# - 用于 C# 静态字典的 VS 2008 Intellisense

c# - 如何从.NET调用Lua函数

cookies - 如何保留使用 MCV5/OWIN 更新的 cookie 声明

c# - 对 302 状态代码使用 handleexeption 注释时如何指定位置

c# - 强制重新下载 nuget 包

c# - 在 Identity Server 4 中为 OpenID Connect 注册 IIdentityServerInteractionService

asp.net - 为什么用户将 ASP.NET 4.6 应用程序本地部署到 IIS 10 服务器后无法进行身份验证?